2

For some reason this function won't return the value ciao:

$a = "ciao";

function a() {
    return $a;
}

I have no idea why.

1

3 Answers 3

4

Functions can only return variables they have in their local space, called scope:

$a = "ciao";

function a() {
    $a = 'hello`;
    return $a;
}

Will return hello, because within a(), $a is a variable of it's own. If you need a variable within the function, pass it as parameter:

$a = "ciao";

function a($a) {
    return $a;
}
echo a($a); # "ciao"

BTW, if you enable NOTICES to be reported (error_reporting(-1);), PHP would have given you notice that return $a in your original code was using a undefined variable.

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

Comments

3

In PHP, functions don't have access to global variables. Use global $a in body of the function or pass the value of $a as parameter.

1 Comment

Don't suggest using global, suggest using a function parameter instead.
2

$a is not in scope within the function.

PHP does not work with a closure like block scope that JS works with for instance, if you wish to access an external variable in a function, you must pass it in which is sensible, or use global to make it available, which is frowned on.

$a = "ciao";

function a() {
    global $a;
    return $a;
}

or with a closure style in PHP5.3+

function a() use ($a) {
    return $a;
}

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.