我有一个小的PHP片段。 如何从主类中为全局分配新值? 示例:
$GlobalValue = 0;
class SampleModuleController extends SampleController {
public function doSomething() {
$NewValue = 1;
$GlobalValue = $NewValue
}
}
echo $GlobalValue;
//This always echo's 0, When I try to output or print outside the class or use somewhere above in the php code.
//I need to be able to assign the new value from within my class
//and the function doSomething so it should be 1
您可以在方法doSomething()
中传递参数作为引用,然后调用该函数,传递变量$GlobalValue
。 但是,不建议使用全局变量。 您应该考虑将代码更多地改为OOP。
$GlobalValue = 0;
class SampleModuleController extends SampleController {
public function doSomething(&$variable) {
$variable = 1;
}
}
$ModuleController = new SampleModuleController();
$ModuleController->doSomething($GlobalValue);
echo $GlobalValue; //print 1