PHP Question: Scope Resolution

6th April 2011

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 variables 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 function 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.

Comments

Permalink

I like the idea of this series, but what if you provided the answer 24h after you posted the question? I mean, let's see what the readers think about it? It might bring pretty interesting answers.

Mihai Baboi (Thu, 04/07/2011 - 06:24)

Permalink

Nice suggestion Mihai I might do that with the next question and see what happens. Would you belive that I once asked this question to a room of developers who used PHP every day and only 30% got it right?

Add new comment

The content of this field is kept private and will not be shown publicly.