在一个消息传递项目中,我有两个类,数字和消息。第一个类处理数字,第二个类处理消息。
number->recive()
应该调用 message->getPass()
。
然后 message->getPass
应该生成一个密码,并使用 message->send()
将其回复给用户。
并且有很多这样的情况,我希望在那个和那个...
我在消息类的 __constructor()
中尝试了 $this->number = new number()
,反之亦然,
但出现 fatal error :允许的内存大小为 33554432 字节已耗尽(已尝试分配 65488 字节)。
我认为错误原因很明显,我导致了实例化的无限循环。
有没有办法让两个类互相使用? 正确的方法是什么?
谢谢
编辑 0:感谢超快速的回答/评论!
编辑 1: 我看到了这个问题How to create two classes in C++ which use each other as data?我不知道那些星号到底是什么意思,也不知道我是否可以在 php 中使用它!
编辑 2: 关于导致错误的代码,简单地说:
测试.php:
include_once './number.php';
$number = new number();
$number->recive();
数字.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");
}
...
}
消息.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");
}
...
}
编辑 3:
某种解决方案可能是这样的:
为每个类添加一个load
方法:
public function load($className) {
require_once $className . '.php';
$this->{$className} = new $className();
}
所以你应该在我需要的时候调用$this->load('number')
从number.php加载number类,然后这样使用它$this->number->numberMethod()
.
最佳答案
我会建议你 - 正如杰夫在评论中所说 - 创建一个同时使用它们的第三个类。
但是,您的问题的快速解决方案:
消息类:
private $number;
public function __construct() {
$this->number = new Number($this);
}
数字类:
private $message;
public function __construct($msg) {
$this->message = $msg;
}
关于php - 创建两个相互使用的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18173784/