2010-08-25 43 views
3

我知道你可以一個函數的返回值賦值給一個變量,並使用它,就像這樣:將函數的結果賦值給PHP類中的變量? OOP怪誕

function standardModel() 
{ 
    return "Higgs Boson"; 
} 

$nextBigThing = standardModel(); 

echo $nextBigThing; 

所以有人告訴我爲什麼下面不工作?還是它尚未實施?我錯過了什麼嗎?

class standardModel 
{ 
    private function nextBigThing() 
    { 
     return "Higgs Boson"; 
    } 

    public $nextBigThing = $this->nextBigThing(); 
} 

$standardModel = new standardModel; 

echo $standardModel->nextBigThing; // get var, not the function directly 

我知道我可以做到這一點:

class standardModel 
{ 
    // Public instead of private 
    public function nextBigThing() 
    { 
     return "Higgs Boson"; 
    } 
} 

$standardModel = new standardModel; 

echo $standardModel->nextBigThing(); // Call to the function itself 

但在我的項目的情況下,所有的存儲在類的信息是預定義的公共瓦爾,除了他們中的一個,這需要在運行時計算該值。

我希望它一致,所以我或任何其他使用此項目的開發人員都必須記住,一個值必須是函數調用,而不是var調用。

但是不要擔心我的項目,我主要只是想知道爲什麼PHP解釋器中的不一致?

很明顯,這些例子是爲了簡化事情而編寫的。請不要質疑「爲什麼」我需要把這個功能放在課堂上。我不需要關於正確的面向對象的教訓,這只是一個概念證明。謝謝!

回答

7
public $nextBigThing = $this->nextBigThing(); 

您只能initialize class members with constant values。即此時您不能使用函數或任何類型的表達式。而且,這個類在這個時候還沒有完全加載,所以即使它被允許了,當它仍然被構造時,你也許不能自己調用​​它自己的函數。

這樣做:

class standardModel { 

    public $nextBigThing = null; 

    public function __construct() { 
     $this->nextBigThing = $this->nextBigThing(); 
    } 

    private function nextBigThing() { 
     return "Higgs Boson"; 
    } 

} 
+0

DOH爲什麼我沒有想到的是嘗試。謝啦。 – Jay 2010-08-25 02:47:10

6

,除非該值是恆定的數據類型不能默認值分配給這樣的特性(如字符串,整數...等)。任何基本上處理代碼的東西(例如函數,甚至$ _SESSION值)都不能被指定爲屬性的默認值。你可以做的事情就是在構造函數中指定屬性的值。

class test { 
    private $test_priv_prop; 

    public function __construct(){ 
     $this->test_priv_prop = $this->test_method(); 
    } 

    public function test_method(){ 
     return "some value"; 
    } 
} 
-2
class standardModel 
{ 
// Public instead of private 
public function nextBigThing() 
{ 
    return "Higgs Boson"; 
} 
} 

$standardModel = new standardModel(); // corection 

echo $standardModel->nextBigThing();