您可以使用$_GLOBALS
,但这是“不好的做法”。所以,
1:使用return
:
<?php
function getName(){
$name = 'Smith';
return $name;
}
function sayMyName(){
$name = getName();
echo $name;
}
sayMyName();
?>
显示:
Smith
2:使用references
:
<?php
function getName(&$name){
$name = 'Smith';
}
function sayMyName(){
getName($name);
echo $name;
}
sayMyName();
?>
显示:
Smith
3:返回array
多个变量:
<?php
function getName(){
$surname = 'Smith';
$name = 'John';
return array($surname, $name);
}
function sayMyName(){
list($surname, $name) = getName();
echo $name, ' ', $surname;
}
sayMyName();
?>
显示:
John Smith
4.object
为多个变量返回自定义:
<?php
function getName(){
$surname = 'Smith';
$name = 'John';
$buffer = new stdClass();
$buffer->name = $name;
$buffer->surname = $surname;
return $buffer;
}
function sayMyName(){
$obj = getName();
echo $obj->name, ' ', $obj->surname;
}
sayMyName();
?>
显示:
John Smith
5. 使用anonymous function
withuse
语句 and references
:
<?php
function sayMyName(){
$surname = $name = 'Unknown';
$temp = function() use (&$name, &$surname){
$surname = 'Smith';
$name = 'John';
};
$temp();
echo $name, ' ', $surname;
}
sayMyName();
?>
显示:
John Smith