如何在类方法中正确使用静态变量?

时间:2016-09-23 03:21:51

标签: php class variables methods static

我正在尝试在PHP中执行此代码:

class T {

    public $y = 4;

    public function y() { return $this->y; }

    public function q()
    {
        static $j = $this->y;   
        echo $j;
    }
}

$r = new T();
$r->q();

我收到以下错误:

Fatal error: Constant expression contains invalid operations in C:\xampp\htdocs\dermaquality\test.php on line 13
static $j = $this->y; 

如果我手动设置值,则没有问题,但如果我设置调用y()或$ this-> y的值,则会出现该错误。 我不知道为什么?

1 个答案:

答案 0 :(得分:1)

将值赋给静态变量,这些变量是表达式的结果,会导致解析错误。

static $int = 0;          // correct 
static $int = 1+2;        // wrong  (as it is an expression)
static $int = sqrt(121);  // wrong  (as it is an expression too)