2016-09-23 88 views
1

我想在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的值會得到該錯誤。 我不知道爲什麼?

+0

在這裏你去:http://php.net/manual/fr/language.oop5.static.php – olibiaz

+0

靜態屬性,不能使用箭頭運營商通過對象訪問 - >。 http://php.net/manual/en/language.oop5.static.php – developer

回答

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) 
相關問題