Create two classes that use each other?

In a messaging project, I have two classes, a number and a message. The first class does stuff about numbers, and the second handles messages.

number->recive() should call message->getPass() . then message->getPass should create a password and respond to it with the user using message->send() .

and there are many situations like this that I want this class in this and that ...

I tried $this->number = new number() in the __constructor() message class and vice versa, but got a fatal error: the allowed memory size of 33554432 bytes was exhausted (tried to allocate 65488 bytes).

I think the cause of the error is obvious, I invoke an endless instance creation cycle.

Is there a way to have two classes that use each other? What is the right way?

thanks

Edit 0: Thanks for the super quick answers / comments!

Edit 1: I saw this question How to create two classes in C ++ that use each other as data? I do not know what exactly these stars mean, and if I can use it in php!

Edit 2: about the codes caused by the error, simply:

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:

Maybe this could be some solution:

Add a load method for each class:

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

so you have to call $this->load('number') to load the number class from number.php when I need it, and then use it this way $this->number->numberMethod() .

+4
source share
2 answers

I would advise you, as Jeff said in the commentary, to create a third class that uses both of them.

However, a quick fix for your problem:

Message Class:

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

Room class:

 private $message; public function __construct($msg) { $this->message = $msg; } 
+2
source

You can have one or both classes single-point, which will prevent the need to create one of them more than once ... add a static getInstance () method for both, which either returns a previously constructed instance or a new one ... see "singleton pattern", and you will see how it works.

-one
source

Source: https://habr.com/ru/post/1496423/


All Articles