Variable scope, constants and include
When a program grows, a single file becomes impossible to read. Two ideas let you tidy it up: controlling where each variable lives (the scope) and splitting the code into several files loaded with include and require. In this lesson you will understand why a function does not "see" outside variables, how to keep a value between calls with static, how to define constants and how to organize your project into files with safe paths.
Local and global scope
A variable created inside a function is local: it exists only while the function runs. A variable created outside is global, but functions do not see it automatically, unlike in other languages. There is the global keyword and the $GLOBALS array, but avoid them: they make a function's behavior depend on something invisible and make testing harder. The right way to give data to a function is to pass it as parameters and receive the result with return.
<?php
declare(strict_types=1);
$rate = 0.21; // global
function priceWithTax(float $price): float
{
// echo $rate; // Warning: Undefined variable $rate (not visible here)
return $price * 1.21;
}
// Correct: pass it as an argument
function priceWithRate(float $price, float $rate): float
{
return $price * (1 + $rate);
}
echo priceWithRate(100.0, $rate), "\n"; // 121
// static keeps a local value between calls
function nextId(): int
{
static $id = 0;
$id++;
return $id;
}
echo nextId(), nextId(), nextId(), "\n"; // 123Constants
A constant holds a value that does not change while the program runs: the application name, a maximum limit, a fixed percentage. It is declared with const at the top level of the file or with define(). It has no $ sign and by convention is written in UPPERCASE with underscores. Constants are visible everywhere in the program, including functions, without the scope problem. With const the value must be known at compile time; with define() you can use an expression computed at runtime.
include, require and __DIR__
To split code, write functions in one file and load it from another. include raises a warning if the file does not exist and the program continues; require raises a fatal error and stops, which is right for essential code. The _once variants avoid loading the same file twice, which would cause the "Cannot redeclare function" error. Relative paths depend on the directory the script is launched from and fail easily. Always use __DIR__, which is the folder of the current file.
<?php
// File: src/helpers.php
declare(strict_types=1);
const TAX_RATE = 0.21;
function money(float $amount): string
{
return number_format($amount, 2, '.', ',') . ' EUR';
}<?php
// File: index.php
declare(strict_types=1);
require_once __DIR__ . '/src/helpers.php';
$price = 1000.0;
echo money($price * (1 + TAX_RATE)), "\n"; // 1,210.00 EUROne more detail about constants: they also exist inside classes, something you will see in week 6. And remember that a constant cannot be reassigned; trying to do so causes an error, which is exactly what we want for values that must never change.
检验所学
第 1 / 1What is the difference between include and require if the file does not exist?
✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符