2010-07-02 18 views
10

有沒有方法可以在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的未來版本中的一個,有一天可能嗎?

回答

10

除了已經提到的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提供代碼幫助。

+0

不錯的選擇,完美的文件目的。 – 2010-07-02 11:19:01

2

不可以。您可以使用type hinting作爲函數參數,但不能聲明變量或類屬性的類型。

6

你在找什麼叫做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那樣廣爲流傳。

PHP Manual on Type Hinting

+1

需要注意的是,TypeHinting對於標量類型還不可用(尚)。 – Gordon 2010-07-02 11:10:56

+0

@戈登:是的。但是當然你可以在方法中檢查一個特定類型的短if條件。如果它不滿意,按給定的參數拋出一個異常。 – 2010-07-02 11:41:10

+0

@faileN是的,類似[is_scalar()](http://de3.php.net/manual/en/function.is-scalar.php)或任何特定的is_ *函數。 – Gordon 2010-07-02 12:09:36

0

可以指定對象的類型,而通過型提示在一個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; 
    } 
} 
+0

我不知道有可能以這種方式重載一個方法。尼斯。 – Cedric 2010-07-02 12:21:52

相關問題