2013-03-22 27 views
1

爲什麼我不能傳遞一個返回字符串的函數作爲函數的參數,其中參數的類型是string?爲什麼我不能傳遞一個返回字符串的函數作爲函數的參數,其中參數的類型是string?

例如:

function testFunction(string $strInput) { 
    // Other code here... 
    return $strInput; 
} 

$url1 = 'http://www.domain.com/dir1/dir2/dir3?key=value'; 
testFunction(parse_url($url1, PHP_URL_PATH)); 

上面的代碼返回一個錯誤:

Catchable fatal error: Argument 1 passed to testFunction() must be an instance of string...

我怎樣才能做到這一點?

+1

PHP是使用Javascript風格聲明變量時,不需要你來聲明一個變量類型鬆散類型的語言。 – 2013-03-22 01:25:28

+1

除了你的類型暗示的問題,你應該注意到parse_url返回一個數組,你似乎期待一個字符串。 – Jeemusu 2013-03-22 01:33:21

+0

你並不孤單:http://yatb.giacomodrago.com/en/post/1/php-is-not-easy-as-it-may-seem.html,告誡4 – gd1 2013-03-22 01:48:23

回答

1

PHP類型提示不支持像字符串,整數,布爾值等標量類型。它只支持對象(通過指定函數原型中類的名稱),接口,數組(自PHP 5.1起)或可調用(自PHP 5.4起)。

因此,在您的示例中,PHP認爲您期待的是一個來自或從中繼承的對象,或者實現了一個名爲「string」的接口,這不是您要做的。

PHP Type Hinting

+0

感謝您的迴應...好吧,所以鍵入提示是關於爲方法參數強制執行類型安全性,並且不適用於像string,int,bool等簡單類型...因此,我只是將其忽略掉...... – user2109254 2013-03-22 03:18:34

1

非常規的答案,但你真的想爲一個字符串類型的提示,你可以爲它創建一個新的類。

class String 
{ 
    protected $value; 

    public function __construct($value) 
    { 
     if (!is_string($value)) { 
      throw new \InvalidArgumentException(sprintf('Expected string, "%s" given', gettype($value))); 
     } 

     $this->value = $value; 
    } 

    public function __toString() 
    { 
     return $this->value; 
    } 
} 

你可以用它

$message = new String('Hi, there'); 
echo $message; // 'Hi, there'; 

if ($message instanceof String) { 
    echo "true"; 
} 

Typehint例如

function foo(String $str) { 

} 
+0

感謝您的回覆。我在這裏結束的原因是我正在編寫一個方法來修剪前後的'/'從路徑字符串,因爲我想比較相對路徑。 (我是PHP新手,來自C#背景)。所以我做了一些搜索並找到了ltrim的方法,當我右鍵單擊它並進入定義(我正在使用Visual Studio的PHP Tools作爲我的IDE)時,我來到以下定義: function ltrim(string $ str ,字符串$ charlist){/ *函數實現* /} 所以這導致我創建我自己的方法,以同樣的方式接受一個字符串。 – user2109254 2013-03-22 03:09:02

+0

我實際上並不知道什麼類型的提示是......以下評論不給IDE它需要什麼它需要intellisense方法簽名: /** *從字符串的開頭去掉空格(或其他字符) 。 (字符串) * * ATparam string $ str輸入字符串。 * ATparam string $ charlist您還可以通過charlist參數指定要刪除的字符。只需列出您想要剝離的所有角色。用..你可以指定一個字符範圍。 * *返回字符串 * / – user2109254 2013-03-22 03:14:28

相關問題