Error when passing string into method with type hinting

后端 未结 5 2077
北荒
北荒 2020-12-20 11:11

In the code below I call a function (it happens to be a constructor) in which I have type hinting. When I run the code I get the following error:

Catchable fatal

5条回答
  •  无人及你
    2020-12-20 11:54

    Just remove string from constructor (not supported) , it should work fine eg:

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

    Working Example:

    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;
    

提交回复
热议问题