2013-02-14 96 views
1

有人可以向我解釋這個嗎?

這兩種方法有什麼區別?

function some_function($foo) 
    { 
    } 

function some_function(foo $foo) 
    { 
    } 
在我的情況

public function validate_something(notice $notice, $tok_id, $captcha) 
{ 
    if(something === true) { 
     $notice->add('info', 'Info message'); 
    } else { 
     $notice->add('error', 'Error message'); 
    } 
} 

$通知書類通知的對象

class notice { 

    private $_notice = array(); 

    public function get_notice(){ 
     return $this->_notice; 
    } 

    public function add($type, $message) { 
     $this->_notice[$type][] = $message; 
    } 
    ... 
} 

回答

6

這就是所謂的type hinting

function some_function($foo) 
{ 
} 

期望一個參數傳遞到some_function當它被稱爲

function some_function(bar $foo) 
{ 
} 

來料的數據類型(類,抽象的或接口,或陣列)巴的參數傳遞到some_function當它被稱爲....如果你傳遞一個參數,它是此數據類型的不是,你會得到開捕致命錯誤

編輯

什麼是T的值ype暗示?

  • 因爲你的代碼並不那麼就需要使用is_ainstance_of到 驗證參數。
  • 減少防禦性編碼器的編碼。
  • 函數/方法是自我記錄的參數。
1

使用這種方法:

function some_function($foo) { 
} 

你希望在你的功能$foo

內部調用有了這一個參數:

function some_function(foo $foo) { 
} 

你期待一個參數叫$foo但它必須是foo類型(foo類的對象)

相關問題