有沒有方法可以在PHP中指定對象屬性的類型? 例如,我有這樣的:在PHP中指定類的對象類型
class foo{
public bar $megacool;//this is a 'bar' object
public bar2 $megasupercool;//this is a 'bar2' object
}
class bar{...}
class bar2{...}
如果沒有,你知道它是否會在PHP的未來版本中的一個,有一天可能嗎?
有沒有方法可以在PHP中指定對象屬性的類型? 例如,我有這樣的:在PHP中指定類的對象類型
class foo{
public bar $megacool;//this is a 'bar' object
public bar2 $megasupercool;//this is a 'bar2' object
}
class bar{...}
class bar2{...}
如果沒有,你知道它是否會在PHP的未來版本中的一個,有一天可能嗎?
除了已經提到的TypeHinting,您可以記錄屬性,例如,
class FileFinder
{
/**
* The Query to run against the FileSystem
* @var \FileFinder\FileQuery;
*/
protected $_query;
/**
* Contains the result of the FileQuery
* @var Array
*/
protected $_result;
// ... more code
的@var annotation
將有助於有些IDE提供代碼幫助。
不可以。您可以使用type hinting作爲函數參數,但不能聲明變量或類屬性的類型。
你在找什麼叫做Type Hinting,並且在PHP 5/5.1之後的函數聲明中部分可用,但不是你希望在類定義中使用它的方式。
這工作:
<?php
class MyClass
{
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
但這並不:
class MyClass
{
public OtherClass $otherclass;
我不認爲這是對未來的計劃,至少我不知道它正在計劃對於PHP 6.
但是,您可以在對象中使用getter and setter functions執行您自己的類型檢查規則。儘管如此,它不會像OtherClass $otherclass
那樣廣爲流傳。
可以指定對象的類型,而通過型提示在一個setter-方法的參數注入對象到變種像這樣:
class foo
{
public bar $megacol;
public bar2 $megasupercol;
function setMegacol(bar $megacol) // Here you make sure, that this must be an object of type "bar"
{
$this->megacol = $megacol;
}
function setMegacol(bar2 $megasupercol) // Here you make sure, that this must be an object of type "bar2"
{
$this->megasupercol = $megasupercol;
}
}
我不知道有可能以這種方式重載一個方法。尼斯。 – Cedric 2010-07-02 12:21:52
不錯的選擇,完美的文件目的。 – 2010-07-02 11:19:01