相关疑难解决方法(0)

将字符串传递给带有类型提示的方法时出错

在下面的代码中,我调用一个函数(它碰巧是一个构造函数),我在其中有类型提示.当我运行代码时,我收到以下错误:

可捕获的致命错误:传递给Question :: __ construct()的参数1必须是字符串的实例,给定字符串,在第3行的run.php中调用,在第15行的question.php中定义

从我可以告诉我错误告诉我该函数期望一个字符串,但传递了一个字符串.为什么不接受传递的字符串?

run.php:

<?php
require 'question.php';
$question = new Question("An Answer");
?>
Run Code Online (Sandbox Code Playgroud)

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;
   }
}
?>
Run Code Online (Sandbox Code Playgroud)

php type-hinting

21
推荐指数
2
解决办法
6225
查看次数

标签 统计

php ×1

type-hinting ×1