kettlepot
kettlepot

Reputation: 11011

Function doesn't return value

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

$a = "ciao";

function a() {
    return $a;
}

I have no idea why.

Upvotes: 2

Views: 3364

Answers (3)

hakre
hakre

Reputation: 198209

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.

Upvotes: 4

Orbling
Orbling

Reputation: 20612

$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;
}

Upvotes: 2

duri
duri

Reputation: 15351

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.

Upvotes: 3

Related Questions