Friday, 10 August 2018

PHP Question: Scope Resolution

Question

What is printed after the following code has been run?
  1. function calc() {
  2. $a = 1000;
  3. return $a;
  4. }
  5.  
  6. $a = 1;
  7. calc();
  8. print $a;
Answer
The answer here is "1", and is an example of what is called 'scope resolution'. Essentially, anything that happens inside the calc() function will stay inside the function, so any varaiables that are created are thrown away after the function has completed its task. Therefore, variable $a that is defined outside the function is a completely different variable to the $a defined inside the funciton and so setting the value inside the function will do nothing to the variable outside.
It is possible to change the value of a variable from inside a function, but that is only if the variable has been passed by reference, which the example above doesn't do.

0 comments:

Post a Comment