php – 创建两个互相使用的类?
在消息传递项目中,我有两个类,数字和消息.第一类是关于数字的东西,第二类是消息处理.
number-> recive()应该调用message-> getPass(). 并且有很多这样的情况,我想要这个类,在这个…… 我在消息类的__constructor()中尝试了$this-> number = new number(),反之亦然, 我认为错误原因是显而易见的,我正在造成一个无限循环的实例化. 有没有办法让两个相互使用的课程? 谢谢 编辑0:感谢超快的答案/评论! 编辑1: 编辑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"); } ... } 爱德3: 某种解决方案可能是这样的: 为每个类添加一个加载方法: public function load($className) { require_once $className . '.php'; $this->{$className} = new $className(); } 所以你应该在需要的时候调用$this-> load(‘number’)从number.php加载数字类,然后以这种方式使用它$this-> number-> numberMethod(). 解决方法
我会建议你 – 正如杰夫在评论中所说 – 创建一个使用它们的第三类.
但是,快速解决您的问题: 消息类: private $number; public function __construct() { $this->number = new Number($this); } 编号类: private $message; public function __construct($msg) { $this->message = $msg; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |