php的類型約束

來源:互聯網
上載者:User

標籤:des   style   blog   http   java   color   使用   io   

//如下面的類class MyClass{    /**     * 測試函數     * 第一個參數必須為 OtherClass 類的一個對象     */    public function test(OtherClass $otherclass) {        echo $otherclass->var;    }    /**     * 另一個測試函數     * 第一個參數必須為數組      */    public function test_array(array $input_array) {        print_r($input_array);    }}    /**     * 第一個參數必須為遞迴類型     */    public function test_interface(Traversable $iterator) {        echo get_class($iterator);    }        /**     * 第一個參數必須為回調類型     */    public function test_callable(callable $callback, $data) {        call_user_func($callback, $data);    }}
// OtherClass 類定義
class OtherClass {
    public $var = ‘Hello World‘;
}

PHP 5 可以使用類型約束。函數的參數可以指定必須為對象(在函數原型裡面指定類的名字),介面,數組(PHP 5.1 起)或者 callable(PHP 5.4 起)。不過如果使用 NULL 作為參數的預設值,那麼在調用函數的時候依然可以使用 NULL 作為實參。

如果一個類或介面指定了類型約束,則其所有的子類或實現也都如此。

類型約束不能用於標量類型如 int 或 string。Traits 也不允許。

所以:

// 兩個類的對象$myclass = new MyClass;$otherclass = new OtherClass;// 致命錯誤:第一個參數必須是 OtherClass 類的一個對象$myclass->test(‘hello‘);// 致命錯誤:第一個參數必須為 OtherClass 類的一個執行個體$foo = new stdClass;$myclass->test($foo);// 致命錯誤:第一個參數不能為 null$myclass->test(null);// 正確:輸出 Hello World $myclass->test($otherclass);// 致命錯誤:第一個參數必須為數組$myclass->test_array(‘a string‘);// 正確:輸出數組$myclass->test_array(array(‘a‘, ‘b‘, ‘c‘));// 正確:輸出 ArrayObject$myclass->test_interface(new ArrayObject(array()));// 正確:輸出 int(1)$myclass->test_callable(‘var_dump‘, 1);

類型約束不只是用在類的成員函數裡,也能使用在函數裡

/** * [testdoc description] * @param  string $q * @param  int    $t * @param  array  $y * @param  object $o * @return [type] */function testdoc(string $q,int $t,array $y,object $o){    var_dump($q);    var_dump($t);    var_dump($y);    var_dump($o);}$obj = new stdClass();testdoc("string",5,array(1,2),$obj);

我上面的測試代碼將會報錯,因為第一個參數希望是string類的執行個體,第二個參數希望是int類的執行個體,第四個參數希望是object類的執行個體,

然而提供的第一個參數為string字串,第二個為int整形,第四個為stdClass類的執行個體,都會報致命錯誤,這是由於php語言在string,int都不是對象,而在c#和java裡面這樣的基礎類型也是對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.