0

There is no problem here but this has been on my mind and I couldn't find the answer anywhere. If I have a variable being populated with a function, does the function only get called when that variable is referenced? Here's and example:

function foo(){

    $foo = "Foo";
    return $foo;

}

$foo = foo();

echo $foo;

In that example I am referencing $foo outside of the function with echo. If I weren't to reference that variable would foo() still be called?

I guess it doesn't really matter I was just wondering.

1
  • 2
    When you say $foo = foo();, you're saying assign that variable to the result of evaluating that function. It will assign it right then and there, so yes, the function will be run. Commented Jun 15, 2013 at 23:29

2 Answers 2

4

The function gets called when the variable is created.

When a variable is created it's contents is evaluated and memorized.

This is the best I can explain the process :)

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

2 Comments

That's what I was thinking. Thanks for the time.
I like to also remember that evaluation is done from right to left on assignment, and left to right on comparison. :)
1

PHP parses the full source,to check for syntax errors and then produces the tokenized form of the script into memory. This is then interpreted during the execution phase. The value of a token is the bytecode/opcode value that represent what action to perform within the life cycle of the processing thread.

  • $foo - In your example there is 2 independent $foo variables (there not the same) in memory there is a reference to the $foo in your function and the $foo outside the functions scope.

  • foo() - The foo function is called when the thread cycle hits $foo = foo();, the opcodes for the foo function are loaded into memory on script initialisation.

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.