Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

php - Error when passing string into method with type hinting

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 error: Argument 1 passed to Question::__construct() must be an instance of string, string given, called in run.php on line 3 and defined in question.php on line 15

From what I can tell the error is telling me that the function is expecting a string but a string was passed. Why isn't it accepting the passed string?

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;
   }
}
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PHP doesn't support type hinting for scalar values. Currently, it's only possible for classes, interfaces and arrays. In your case, it's expecting an object that is an instance of a "string" class.

There is currently an implementation supporting this in the SVN trunk version of PHP, but it's undecided if that implementation will be the one that gets released in future versions of PHP, or if it will be supported at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...