首页 > 解决方案 > 构造函数导致无限循环

问题描述

我正在尝试完成这个 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() {}

我不完全理解这是如何工作的......我想了解这里发生了什么。非常感谢任何有关解释其工作原理的帮助。

标签: phpoop

解决方案


在 PHP 之前__construct,您将通过将方法命名为与类相同的名称来创建构造函数。这仍然受支持,但在 PHP 7 中已弃用。这意味着如果您的Answer类没有现代构造函数 ( __construct),则该answer方法将作为构造函数调用。由于它返回 a new Answer,因此将在新对象上再次调用构造函数,一次又一次。您有一个无限递归,一旦内存耗尽就会引发错误。

我只能猜测这个练习的原因是什么。但是您也可以只返回$this,get和。如果您希望您的类支持“链接”,这就是您通常所做的。当然,在现实世界中,这些方法也会做其他事情。theanswer


推荐阅读