PHP Question: Scope Resolution

Question

What is printed after the following code has been run?

function calc() {
    $a = 1000;
    return $a;
}

$a = 1;
calc();
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

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.

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?

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
8 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.