2012-11-05 39 views
0

我想指定可以賦予函數的數據類型。您可以指定給定函數的參數的數據類型(PHP5)

在這個演示代碼(作爲一個例子),我想指定給"__construct()"函數的參數的數據類型,這樣只需要INT$id,類型"example2"Objects$some_object

你有什麼想法我可以做到這一點嗎?

<?php 

    class example1{ 

     private $id; 
     private $example2; 
     function __construct($id,$some_object){ 
      $this->id = $id; 
      $this->object = $some_object; 
     } 

     function do_something(){ 
      $this->example2->moep(); 
     } 

    } 
    class example2{ 
     public function moep(){ 
      print("MOEP!!!"); 
     } 
    } 
?> 

回答

0

檢查類型,如果需要拋出異常:

function __construct($id,$some_object){ 
    if (!is_int($id)) throw new UnexpectedValueException("Argument 1 must be an integer"); 
    if (!is_object($some_object)) throw new UnexpectedValueException("Argument 2 must be an instance of any object"); 

    $this->id = $id; 
    $this->object = $some_object; 
} 
+0

這也很有幫助.. 非常感謝你:) – user1800353

相關問題