2013-02-08 21 views
0

我試圖用這個方法:如何僅在PHP方法參數中聲明字符串?

public function setMessage(string $message){ 
    $this->message = $message; 
} 

然後我得到這個錯誤:

Catchable fatal error: Argument 1 passed to notifier::setMessage() must be an instance of string, string given

顯然PHP是解釋string作爲類名。有沒有看起來像做出這種聲明的解決方案?

回答

5

Typehinting只能在對象中使用,與陣列的例外。

Manual

Type hints can not be used with scalar types such as int or string. Traits are not allowed either.

+1

唯一例外的是'array'。 – Leri

+0

謝謝 - 更新。 – MrCode

+0

換句話說:只對非標量類型進行打字處理。 – lafor

1

PHP是一種鬆散類型的語言,它並不真正在意類型,並會猜測。你只能在函數聲明中將變量限制到類,所以刪除string,一切都會好的。 :)

如果你真的想確定它是一個字符串使用gettype()cast該變量爲一個字符串。

注(從上PHP.net型juggline):

Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

$foo = 10;   // $foo is an integer 
$str = "$foo";  // $str is a string 
$fst = (string) $foo; // $fst is also a string