Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function doesn't return value

Tags:

function

php

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

$a = "ciao";

function a() {
    return $a;
}

I have no idea why.

like image 478
Gabriele Cirulli Avatar asked Jan 21 '26 19:01

Gabriele Cirulli


2 Answers

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.

like image 182
hakre Avatar answered Jan 23 '26 08:01

hakre


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.

like image 28
duri Avatar answered Jan 23 '26 08:01

duri