创建两个互相使用的类?

时间:2013-08-11 15:54:21

标签: php oop

在消息传递项目中,我有两个类,数字和消息。第一类是关于数字的东西,第二类是消息处理。

number->recive()应致电message->getPass()。 然后message->getPass应生成密码,并使用message->send()将其回复给用户。

并且有很多这样的情况,我希望这个类和那个......

我在邮件类$this->number = new number()中尝试__constructor(),反之亦然, 但得到致命错误:允许的内存大小为33554432字节(尝试分配65488字节)。

我认为错误原因是显而易见的,我造成了无限循环的实例化。

有没有办法让两个相互使用的课程? 什么是正确的方法?

由于

编辑0:感谢超快的答案/评论!

编辑1: 我看到了这个问题How to create two classes in C++ which use each other as data?我不知道这些星号是什么意思,如果我可以在php中使用它!

编辑2: 关于代码导致的错误,简单地说:

test.php的:

include_once './number.php';
$number  = new number();
$number->recive();

number.php:

include_once './message.php';
class number {

    public function __construct($numberId = NULL) {
        $this->message = new message();
        $this->pdo = new PDO("mysql:host=localhost;dbname=madb", "root", "root");
    }
    ...
}

message.php:

class message {

    protected $pdo, $rows, $sql, $number;

    public function __construct($messageId = NULL) {
        $this->number = new number();
        $this->pdo = new PDO("mysql:host=localhost;dbname=madb", "root", "root");
    }
    ...
}

Edid 3:

某种解决方案可能是这样的:

为每个类添加load方法:

public function load($className) {
    require_once $className . '.php';
    $this->{$className} = new $className();
}

所以你应该在我需要时调用$this->load('number')从number.php加载数字类,然后以这种方式使用$this->number->numberMethod()

2 个答案:

答案 0 :(得分:2)

我会建议你 - 正如杰夫在评论中所说 - 创建一个使用它们的第三类。

然而,快速解决您的问题:

消息类:

private $number;

public function __construct() {
  $this->number = new Number($this);
}

数字等级:

private $message;

public function __construct($msg) {
  $this->message = $msg;
}

答案 1 :(得分:-1)

你可以让一个或两个类成为单例,这样可以防止需要多次构造其中一个...向两者都添加一个静态getInstance()方法,它返回先前构造的实例或新实例...查看“单身模式”,你会看到它是如何工作的。