首页 > 解决方案 > 两个通信类上的PHP无限循环

问题描述

这是我第一次遇到这个问题,希望您能给我一些解释或一些动力来解决它。

我在这里写了这段代码:

class Foo
{
    public function __construct()
    {
        $this->bar = New Bar();
    }
}

class Bar
{
    public function __construct()
    {
        $this->foo = New Foo();
    }
}

$foo = New Foo();

此代码引发以下错误:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes)

如何让两个类相互通信而不会出现此错误?

编辑:

根据要求,我将更详细地介绍。例如,我编写了两个强制相互通信的类,类似于我当前的项目:

    class UserStatusController
    {
        public function __construct()
        {
            $this->couponController = New CouponController();
        }
        
        private $badStatus = "blocked";
        
        public function hasBadStatus(int $id): bool
        {
            $user = User::where(['id' => $id])->get();
            return $user->status == self::$badStatus ? true : false;
        }
        
        public function actualizeStatus(int $id, string $status): bool
        {
            if ($status == self::$badStatus) {
                
                $this->couponController->deleteCoupon();
                return false;
            }
            
            $user = User::where(['id' => $id])->update(['status' => $status]);
            $this->couponController->createCoupon();

            return true;
        }
    }
    
    class CouponController
    {
        public function __construct()
        {
            $this->userStatusController = New UserStatusController();
        }
        
        public function createCoupon(): bool 
        {
            if ($this->userStatusController->hasBadStatus()) { return false; }
            // create coupon ...
        }
        
        public function deleteCoupon(): bool 
        {
            // delete coupon ...
        }
    }

由于这两个类每个都有另一个类需要的信息,所以它们必须以某种方式交换数据。在上面的示例中,有一个无限循环。

所以问题是,让这两个类相互交谈的最常见方式是什么?

标签: phploopsclassmemorysize

解决方案


在您的代码中,您New Bar();在类 Foo 中启动,然后New Foo()在启动类 Bar 中启动New Bar(),以此类推。

下面的代码返回bool(true)我认为是你试图实现的。

<?php
class Foo
{
    public function foo1()
    {
        return true;
    }
}
class Bar
{
    public function __construct()
    {
        $this->foo = New Foo();
    }
}
$foo = New Foo();
var_dump( $foo->foo1() );

如果您需要其他内容,请编辑您的问题并更具体。另一方面,如果您像这样修改代码:

class Foo
{
    public function foo1()
    {
        return true;
    }
}
class Bar
{
    public function __construct()
    {
        $this->foo = New Foo();
        return $this->foo;
    }
}
$foo = New Bar();
var_dump($foo);

结果是object(Bar)#1 (1) { ["foo"]=> object(Foo)#2 (0) { } }

此外,如果这 2 个函数在同一个文件中,则不需要另一个类。如果它们必须在单独的文件中,您可以编写class bar extends Foo. 有很多 OOP 课程和解释类、功能等的免费视频。


推荐阅读