如何在类方法中正确使用静态变量?
问题描述:
我想在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的值会得到该错误。 我不知道为什么?
答
将值赋给作为表达式结果的静态变量将导致解析错误。
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)
在这里你去:http://php.net/manual/fr/language.oop5.static.php – olibiaz
静态属性,不能使用箭头运营商通过对象访问 - >。 http://php.net/manual/en/language.oop5.static.php – developer