2010-06-24 50 views
21

在下面的代碼中,我調用了一個函數(它恰好是一個構造函數),其中我有類型提示。當我運行的代碼,我得到了以下錯誤:將字符串傳入帶提示類型的方法時出錯

捕獲的致命錯誤:傳遞到問題參數1 :: __構造()必須是字符串,給定的字符串,稱爲run.php第3行的一個實例,在question.php定義上線

從我可以告訴錯誤是告訴我,該函數需要一個字符串,但字符串傳遞。爲什麼它不接受傳入的字符串?

run.php

<?php 
require 'question.php'; 
$question = new Question("An Answer"); 
?> 

question.php

<?php 
class Question 
{ 
    /** 
    * The answer to the question. 
    * @access private 
    * @var string 
    */ 
    private $theAnswer; 

    /** 
    * Creates a new question with the specified answer. 
    * @param string $anAnswer the answer to the question 
    */ 
    function __construct(string $anAnswer) 
    { 
     $this->theAnswer = $anAnswer; 
    } 
} 
?> 

回答

7

只是刪除從構造stringnot supported),它應該工作的罰款如:

function __construct($anAnswer) 
{ 
    $this->theAnswer = $anAnswer; 
} 

工作實施例:

class Question 
{ 
    /** 
    * The answer to the question. 
    * @access private 
    * @var string 
    */ 
    public $theAnswer; 

    /** 
    * Creates a new question with the specified answer. 
    * @param string $anAnswer the answer to the question 
    */ 
    function __construct($anAnswer) 
    { 
     $this->theAnswer = $anAnswer; 
    } 
} 

$question = new Question("An Answer"); 
echo $question->theAnswer; 
3

類型提示只能(自5.1或陣列)用於對象的數據類型,而不是基本的類型,如字符串,整數,浮點數,布爾值

27

PHP不支持標量值的類型提示。目前,它只能用於類,接口和數組。在你的情況下,它期望一個對象是「字符串」的一個實例。

目前有一種在SVN中繼版本的PHP中支持這個功能的實現,但是如果這個實現將會在PHP的未來版本中發佈,或者它將被支持,那麼它還沒有確定。

+0

這是因爲需要PHP標量都按摩到彼此,所以0 ==虛假等。如,你不能鍵入提示標。這對PHP內部進行了很多討論,我是其中一員。 – Fuser97381 2014-11-06 16:24:22

0

「類型聲明」(又名 「類型提示」)可用於自PHP 7.0.0以下類型:

  • bool參數必須是一個布爾值。
  • float參數必須是浮點數。
  • int參數必須是整數。
  • string參數必須是字符串。
  • bool參數必須是布爾值。

以來PHP 7.1.0以下類型:

  • iterable的參數必須是一個數組或一個instanceof Traversable的。

所以從現在開始另一個回答這個問題實際上是(種):

交換機爲您所期望的PHP版本PHP7.x和代碼將工作。

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

相關問題