How does php execute the function assigned to a variable?

Well, I really did not know how to correctly formulate this question, but let me explain.

Suppose I have a variable:

$file = dirname(__FILE__); 

What happens if I assign $file another variable?

 $anotherVariable = $file; 

Does the dirname function dirname every time I assign?

Thanks for any help.

+6
php
source share
4 answers

Not. PHP is required, so the right-hand side of assignment expressions is evaluated, and the result is stored "on the left-hand side" (in the simple and almost universal case, the variable named on the left-hand side).

 $a = $b; // Find the value of $b, and copy it into the value of $a $a = 5 + 2; // Evaulate 5 + 2 to get 7, and store this in $a $a = funcName(); // Evaluate funcName, which is equivalent to executing the code and obtaining the return value. Copy this value into $a 

It gets a little trickier if you assign by reference ($ a = & $ b), but this time we don’t need to worry.

+12
source share

PHP has no such closures.

directory_name ( FILE )

this function returns a string.

$ anotherVariable = $ file;

gives $ anotherVariable the same string value.

therefore, I believe that the answer to your question is β€œno,” it will not be executed every time.

+2
source share

The answer to the main question:

 $a = function(){ echo "Hello!"; }; $a(); 

Answers to minor questions:

 $file = dirname(__FILE__); //means: //"Evaluate/Execute function dirname() and store its return value in variable $file" 

What happens if I assign $ file to another variable?

If we talk about regular assignment ( $anotherVariable = $file; ), then it simply copies the value from $file to $anotherVariable as independent variables.

Does the dirname function execute every time I assign?

No no. Because execution is only performed with () . No () = No execution.

+2
source share

No, anyway.

PHP functions are not identifiers that point to an instance of the Function class, as you can see in Java, ActionScript, JavaScript, etc. Therefore, you cannot save a function reference for a variable. This is why every time you call a function, it is shared, just like you include a () script to execute. Of course, there are differences, but in the context of this question, including include () and function calls are almost identical.

Do not confuse with this case.

 function myFunc() {return 'hello world';} $func = 'myFunc'; $a = $func(); echo $a; // hello world 

Read about this case here. This behavior is special for PHP. Not sure about other languages ​​- maybe somewhere out there. It looks like this, but I never met him.

+1
source share

All Articles