在下面的代码中,我调用一个函数(它碰巧是一个构造函数),我在其中有类型提示.当我运行代码时,我收到以下错误:
可捕获的致命错误:传递给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)
Dan*_*erg 28
PHP不支持标量值的类型提示.目前,它只适用于类,接口和数组.在您的情况下,它期望一个对象是"字符串" 类的实例.
目前在PHP的SVN主干版本中有一个支持这一功能的实现,但如果该实现将是在未来版本的PHP中发布的实现,或者它将完全受支持,则尚未确定.
只需string
从构造函数中删除(不支持),它应该工作正常,例如:
function __construct($anAnswer)
{
$this->theAnswer = $anAnswer;
}
Run Code Online (Sandbox Code Playgroud)
工作实例:
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;
Run Code Online (Sandbox Code Playgroud)