将字符串传递给具有类型提示的方法时出错 [英] 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:
可捕获的致命错误:传递给Question :: __ construct()的参数1必须是字符串的实例,该字符串是给定的,在第3行的run.php中调用并在问题中定义. php 在第 15
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;
}
}
?>
推荐答案
只需从构造函数中删除string
(不支持),它应该可以正常运行,例如:
Just remove string
from constructor (not supported) , it should work fine eg:
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;
这篇关于将字符串传递给具有类型提示的方法时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!