有没有办法在 PHP 中实现以下功能,或者根本不允许这样做? (见下面的注释行)
function outside() {
$variable = 'some value';
inside();
}
function inside() {
// is it possible to access $variable here without passing it as an argument?
}
最佳答案
请注意,不建议使用 global 关键字,因为您无法控制(您永远不知道在应用程序的其他地方使用和更改变量)。但是如果你使用类,它会让事情变得容易得多!
class myClass {
var $myVar = 'some value';
function inside() {
$this->myVar = 'anothervalue';
$this->outside(); // echoes 'anothervalue'
}
function outside() {
echo $this->myVar; // anothervalue
}
}
关于php - 从外部函数(PHP)访问函数中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9646507/