ptvty
ptvty

Reputation: 5664

Create two classes which use each other?

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

number->recive() should call message->getPass(). then message->getPass should produce a password, and reply it to user using message->send().

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

I tried $this->number = new number() in message class's __constructor() and vice versa, but got an Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 65488 bytes).

I think the error reason is obvious, I'm causing an infinite loop of instantiating.

Is There Any Way to Have Two Classes Which Use Each Other? Whats the Right Way to Go?

Thanks

Edit 0: Thanks for super fast answers/comments!

Edit 1: I saw this question How to create two classes in C++ which use each other as data? I don't have any idea what exactly those asterisks mean, and if I can use it in php!

Edit 2: about the codes caused 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:

Some kind of solution maybe this:

Add a load method to each class:

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

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

Upvotes: 4

Views: 1219

Answers (2)

Michael Steuer
Michael Steuer

Reputation: 517

You could have one or both classes be singleton, which would prevent the need to construct either one of them more than once... add a static getInstance() method to both which either returns a previously constructed instance or a new one... look up "singleton pattern" and you'll see how this works.

Upvotes: -1

ComFreek
ComFreek

Reputation: 29424

I would advise you - as jeff said in a comment - to create a third class which uses them both.

However, a quick solution for your problem:

Message class:

private $number;

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

Number class:

private $message;

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

Upvotes: 3

Related Questions