Red Virus
Red Virus

Reputation: 1707

Does the function run when assigned to local variable

Below is the example I put together to understand my confusion. Now my question is, when I make the function into a local variable, does it start to run instantly or does it wait for the local variable to be called.

//Here is the function
function myFunction(){
    return 'Hello Stackoverflow';
}

//Does the functio run at this point
$stackoverflow = myFunction();

//Or does the function run here?
echo $stackoverflow;

Upvotes: 1

Views: 822

Answers (4)

Davis
Davis

Reputation: 846

It will run at the time of assignment:

$stackoverflow = myFunction();

You could assign the function to the variable if you want it called when referencing the variable and not when it's assigned:

$foo = function () {
    return 'Hello Stackoverflow';
};

echo $foo();

Upvotes: 2

Francesco Abeni
Francesco Abeni

Reputation: 4265

You are not actually assigning a function to the variable, but the return value of the function.

And yes, the function is executed when you call it, i.e. when you assign it to the variable.

After that of course you have a variable with a value and you can do whatever you want with it.

Upvotes: 4

bassxzero
bassxzero

Reputation: 5041

You aren't making "the function into a local variable."

In your example the function runs, the string return value is assigned to $stackoverflow, then you echo the string.

I think you are trying to do this.

//Here is the function
function myFunction(){
    return 'Hello Stackoverflow';
}

//Doesn't run yet
$stackoverflow = 'myFunction';

//This runs now
echo $stackoverflow();

Upvotes: 9

rvbarreto
rvbarreto

Reputation: 691

The function run when it is assigned to a value, i.e, at $stackoverflow = myFunction();

Upvotes: 1

Related Questions