I'll try to explain with an example...
Let's say I have two different functions, and one of them has a defined variable. In the second function, I don't wanna write the same variable again, can I simply use the variable from the first function in the second one WITHOUT redefining it in the second function?
Something like:
function a() { $var = "my variable"; } function b() { echo $var; }
Sorry if this questions is a bit silly, but I'm still a beginner =).
Try it out at this Codepad example php function a(){ $a = 1; echo "First: $a, "; ++$a; $b = function() use ($a) { echo "second: $a"; }; return $b; }; $fun = a(); // $fun is now $b & $b has access to $a! $fun(); // Outputs: First: 1, second: 2 ?>
Yes, variables belonging to different function can have same name because their scope is limited to the block in which they are defined. Variables belonging to different functions in a single code can have same name if we declare that variable globally as shown in the following code snippet below .
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
The cleanest solution here is to make A and B methods of a class and have the common variables as private static variables. This removes the messiness of globals and allows both functions to be globally accessible.
class SomeClass { private static $a = 1; public static function a() { self::$a = 2; } public static function b() { echo self::$a; } }
You can then call the functions:
SomeClass::a(); SomeClass::b();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With