构造函数导致无限循环

Jak*_*ake 1 php oop

我正在尝试完成这个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);
Run Code Online (Sandbox Code Playgroud)

当我运行这样的代码时,它给了我错误:

Fatal error: Allowed memory size of 134217728 bytes exhausted
Run Code Online (Sandbox Code Playgroud)

我可以通过在代码中插入以下内容来修复错误:

public function __construct() {}
Run Code Online (Sandbox Code Playgroud)

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

jh1*_*711 6

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

我只能猜出这次练习的原因是什么.但你也可以只返回$thisget,theanswer.如果您希望您的课程支持"链接",那么您通常会这样做.当然,在现实世界中,这些方法也可以做其他事情.