PHP从稍后要使用的函数返回一个字符串?

function foo() {
    $foo1= mysql_query();
    $db_field = mysql_fetch_assoc($foo1);
    $word= $db_field['word'];
    $lower=strtolower($word);
}
foo();
print $lower;

The function above executes a block of code with the endgame being the $lower variable, which is the lowercase of a word from a database. As the code is written above, I get an error saying that $lower is not defined.

I tried returning $lower with return $lower, but that didn't work. How do I keep a variable from a function for later use?

First of all, return $lower at the end of the function is correct. Then you use:

$var = foo();

You just discoverd the scope of a variable. $lower is only availible inside the function, so you cant use it outside of it.

$lower is defined inside the function which have scope only within that function. So trying to access it outside the function will definitely cause proble. You have to return it in the function .Try with :

function foo() {
    $foo1= mysql_query();
    $db_field = mysql_fetch_assoc($foo1);
    $word= $db_field['word'];
    return strtolower($word);  // return the value
}
$lower=foo();   // this will contain the return value of foo()
print $lower;

put your return statement back

...
return $lower;
}

$result = foo();
print $result;

$lower variable used only in the function. it can't work out of the function. Do like this,

function foo() {
    $foo1= mysql_query();
    $db_field = mysql_fetch_assoc($foo1);
    $word= $db_field['word'];
    $lower=strtolower($word);
  return $lower;
}

$lower = foo();
print $lower;

You could actually use 'global' Like This.

    $lower = '';

    function foo() {

        global $lower;

        $foo1= mysql_query();
        $db_field = mysql_fetch_assoc($foo1);
        $word= $db_field['word'];
        $lower=strtolower($word);

    }

    foo();
    print $lower;