Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does php execute a function assigned to variable?

Tags:

php

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.

like image 390
0xdeadbeef Avatar asked May 22 '09 13:05

0xdeadbeef


People also ask

How do you call a function variable in PHP?

There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used.

How does a function work in PHP?

PHP User Defined Functions Besides the built-in PHP functions, it is possible to create your own functions. A function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.

What is the method for assigning variables in PHP?

Declaring PHP variables All variables in PHP start with a $ (dollar) sign followed by the name of the variable. A valid variable name starts with a letter (A-Z, a-z) or underscore (_), followed by any number of letters, numbers, or underscores.

What is a variable function How can we use it PHP give examples?

If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find a function whose name corresponds to value of the variable and executes it. Such a function is called variable function. This feature is useful in implementing callbacks, function tables etc.


1 Answers

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.

like image 125
Adam Wright Avatar answered Oct 04 '22 20:10

Adam Wright