开发者

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.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜