PHP从类内部为变量(globa)分配值

问题描述 投票:0回答:1

我有一个小的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
php variables
1个回答
0
投票

您可以在方法doSomething()中传递参数作为引用,然后通过变量$GlobalValue调用该函数。但是,建议不要使用全局变量。您应该考虑将代码更改为更多OOP。

$GlobalValue = 0;

class SampleModuleController {

    private $newValue = 3;

    public function doSomething(&$variable) {
        $variable = $this->newValue;
    }

}

$ModuleController = new SampleModuleController();
$ModuleController->doSomething($GlobalValue);

echo $GlobalValue; //print 1
© www.soinside.com 2019 - 2024. All rights reserved.