tags:

views:

267

answers:

3

Ok, I didn't really know how to even phrase the question, but let me explain.

Suppose I have a variable:

$file = dirname(__FILE__);

What happens if I assign $file to another variable?

$anotherVariable = $file;

Does the dirname function get executed each time I assign?

Thanks for any help.

+2  A: 

PHP doesn't have closures like that.

dirname(FILE)

this function returns a string.

$anotherVariable = $file;

gives $anotherVariable that same string value.

so I believe the answer to your question is "no", it does not get executed each time.

ctshryock
Closure may be the wrong term, but php functions are not first class citizens
ctshryock
+5  A: 

No. PHP is imperative, so the right hand side of assignment expressions is evaluated, and the result stored "in the" left hand side (in the simple and almost ubiquitous 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

This gets a little more complex when you assign by reference ($a = &$b), but we needn't worry about that for now.

Adam Wright
A: 

No in any case.

PHP's functions are not identifiers which point to instance of class Function as you can see in Java, ActionScript, JavaScript etc... That's why you can't store a link to function itself to a variable. That's why any time you call the function it is in common the same as you include() a script to execute. Sure there are differences, but in context of this question including with include() and calling a function are almost identical.

Don't be confused 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 somwhere there's smth. similar to this, but I've never met it.

Jet