PHP Manual

Local variables in PHP

22. 08. 2019

Local variables are valid only inside the body of **function** or **method** (in object-oriented programming).

If we are working in the context of a regular script, everything happens as expected:

$x = 5;
echo $x; // prints 5

But when we define our own function, the behavior changes slightly:

$x = 5;
function myFunction(): int
$x = 3;
echo $x; // prints 3
echo $x; // prints 5

The reason is that the $x variable exists only in the context of the current function or method. This behavior is intentional.

If we want to pass a value from the surrounding code to a function, we have to call it with the necessary parameters:

echo myFunction(5); // prints 6
function mojeFunction(int $x): int
return $x + 1;

Values are passed into functions using parameters. If you want to pass additional variables into the function beyond the parameters, you can use global variables, but this is not a good idea.

Using local variables makes a huge difference when programming a larger application. If we didn't distinguish the validity of variables across contexts, it would be impossible to guarantee that a variable wouldn't be overridden in a place where we don't count on it (which is why global variables are evil).

$x = 5;
$y = 3;
function sum(int $x, int $y): int
return $x + $y;
echo $x; // prints 5
echo sum($x, $y); // prints 8

Jan Barášek   Více o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Související články

All systems normal.