Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I share variables between different functions in PHP?

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 =).

like image 289
aborted Avatar asked Oct 09 '10 22:10

aborted


People also ask

How can we use same variable in different functions in PHP?

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 ?>

Can you use the same variable name in different functions?

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 .

Are PHP variables global?

$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.


1 Answers

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(); 
like image 147
lonesomeday Avatar answered Sep 24 '22 17:09

lonesomeday