加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 创建两个互相使用的类?

发布时间:2020-12-13 22:49:36 所属栏目:PHP教程 来源:网络整理
导读:在消息传递项目中,我有两个类,数字和消息.第一类是关于数字的东西,第二类是消息处理. number- recive()应该调用message- getPass(). 然后message- getPass应该生成一个密码,并使用message- send()将其回复给用户. 并且有很多这样的情况,我想要这个类,在这个
在消息传递项目中,我有两个类,数字和消息.第一类是关于数字的东西,第二类是消息处理.

number-> recive()应该调用message-> getPass().
然后message-> getPass应该生成一个密码,并使用message-> send()将其回复给用户.

并且有很多这样的情况,我想要这个类,在这个……

我在消息类的__constructor()中尝试了$this-> number = new number(),反之亦然,
但得到致命错误:允许的内存大小为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");
    }
    ...
}

爱德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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读