【问题标题】:How to correctly use static variables in class methods?如何在类方法中正确使用静态变量?
【发布时间】:2017-01-31 19:10:22
【问题描述】:

我正在尝试在 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 的值,我会收到该错误。 不知道为什么?

【问题讨论】:

标签: php class variables methods static


【解决方案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)

【讨论】:

    猜你喜欢
    • 2018-11-22
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 2013-11-28
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多