php - 构造函数导致无限循环
问题描述
我正在尝试完成这个 PHP 挑战,我目前有以下代码:
<?php
/*
Challenge 2: Implement AnswerInterface and get Question to echo "4".
*/
class Question
{
public function __construct(AnswerInterface $answer)
{
echo "What is 2 + 2?\n";
$answer = $answer->get()->the()->answer();
if ($answer instanceof AnswerInterface) {
echo $answer . PHP_EOL;
}
}
}
interface AnswerInterface
{
public function get();
public function the();
public function answer();
}
class Answer implements AnswerInterface
{
public function get()
{
return new Answer();
}
public function the()
{
return new Answer();
}
public function answer()
{
return new Answer();
}
public function __toString()
{
return '4';
}
}
$answer = new Answer;
$question = new Question($answer);
当我像这样运行代码时,它给了我错误:
Fatal error: Allowed memory size of 134217728 bytes exhausted
我可以通过在代码中插入以下内容来修复错误:
public function __construct() {}
我不完全理解这是如何工作的......我想了解这里发生了什么。非常感谢任何有关解释其工作原理的帮助。
解决方案
在 PHP 之前__construct
,您将通过将方法命名为与类相同的名称来创建构造函数。这仍然受支持,但在 PHP 7 中已弃用。这意味着如果您的Answer
类没有现代构造函数 ( __construct
),则该answer
方法将作为构造函数调用。由于它返回 a new Answer
,因此将在新对象上再次调用构造函数,一次又一次。您有一个无限递归,一旦内存耗尽就会引发错误。
我只能猜测这个练习的原因是什么。但是您也可以只返回$this
,get
和。如果您希望您的类支持“链接”,这就是您通常所做的。当然,在现实世界中,这些方法也会做其他事情。the
answer
推荐阅读
- awk - 使用范围表达式过滤表格文件
- google-apps-script - 如何使用 Google Apps 脚本在 Google Forms 中进行简单的身份验证?
- mirth - Mirth -> HL7 到 XML 转换问题
- javascript - Firestore 自定义声明未更新 UI
- javascript - 如何运行编写在外部 js 文件中的 npm 脚本(package.json)?
- nestjs - 具有单独实体定义的迁移
- r - 为分组后的列添加原始值
- c - 在每个文件中创建相同的#define
- javascript - 如何在渲染后动态取消选中和选中星云复选框
- date - 如何计算机器在线的百分比