2013-10-29 40 views
0

是否有可能在PHP中的構造函數中更改靜態類屬性的默認值?Php類和構造函數內的靜態屬性

class Test { 
    public static $property = 'default'; 

    public function __construct() { 
    self::$property = 'new value'; 
    }  
} 

上面的代碼沒有這樣做。 在此先感謝!

編輯

我知道我可以改變類

Test::$property = 'new value'; 
echo Test::$property; 

我在想,如果我能做到這一點類的構造函數裏外的值。

+0

'$ A =新的測試(); echo Test :: $ property;'print'new value' –

+0

你的測試代碼應該可以工作,或許你應該發佈* real *代碼 – AlexP

+0

而不是使用'self :: $ property'你可能會考慮使用'static :: $ property '它允許更多的動態用法:請參閱:http://stackoverflow.com/questions/4718808/php-can-static-replace-self – Luceos

回答

0

在PHP 5.3中,您可以使用遲到的靜態綁定。

在代碼中的 「靜態」 替換 「自我」:

class Test { 
    public static $property = 'default'; 

    public function __construct() { 
    static::$property = 'new value'; 
    }  
} 

它將作品;)

+1

是的,它在初始化類時起作用,但不直接用Test :: $屬性來訪問它,這就是$ test = new Test()的構造函數。測試:: $屬性,然後它的作品完美:) – user558134

+0

我不知道你想這樣做!所以,你必須爲這個屬性寫一個getter。 – TeChn4K

+0

是的,一個吸氣器會做我的工作:) – user558134

0

你忘了雙點:

self::$property = 'new value'; 
+0

這只是一個打字錯誤在這裏 – user558134

+0

好吧,然後我看不到錯誤。應該管用。 – TiMESPLiNTER

0

這是爲我工作。

class Test { 
    public static $property = 'default'; 
    public function __construct() { 
    echo self::$property = 'new value'; // for EXample echo val of property 
    }  
} 
//When create a new object of class it shows/Assigns value of static property 

$test = new Test(); 
echo Test::$property;