6

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.

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Closure may be the wrong term, but php functions are not first class citizens
2

Answer to 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 are talking about regular assignment ( $anotherVariable = $file; ),
it just copies the value from $file to $anotherVariable both are independent variables.

Does the dirname function get executed each time I assign?

No it does not. Because execution is done only with (). No () = No execution.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.