⊗ppPmScGV 214 of 447 menu

Global Variables in PHP

As you already know, external variables are not accessible inside a function:

<?php $num = 1; function func() { $num = 2; } func(); echo $num; // 1 ?>

However, they can be made accessible. To do this, inside the function, the variable must be declared global using the command global. After that, PHP will understand that we are referring to the external variable:

<?php $num = 1; function func() { global $num; // declare as global $num = 2; } func(); echo $num; // 2 ?>

Fix the code so that it works as intended:

<?php $num = 1; function func() { $num++; } func(); echo $num; // should output 2 ?>

Fix the code so that it works as intended:

<?php $num = 1; function func() { $num++; return $num; } echo func(); // should output 2 ?>

Fix the code so that it works as intended:

<?php $num = 1; function func() { return $num; } echo func(); // should output 1 ?>
byenru