9112

$this->a->b->c->d calling methods from a superclass in php

Question:

Hello i want to make something on classes

i want to do a super class which one is my all class is extended on it

____ database class / chesterx _/______ member class \ \_____ another class

i want to call the method that is in the database class like this

$this->database->smtelse(); class Hello extends Chesterx{ public function ornekFunc(){ $this->database->getQuery('popularNews'); $this->member->lastRegistered(); } }

and i want to call a method with its parent class name when i extend my super class to any class

Answer1:

I'm not quite sure what you mean by your last sentence but this is perfectly valid:

class Chesterx{ public $database, $member; public function __construct(){ $this->database = new database; //Whatever you use to create a database $this->member = new member; } }

Answer2:

Consider the Singleton pattern - it usually fits better for database interactions. <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow">http://en.wikipedia.org/wiki/Singleton_pattern</a>.

Answer3:

you could also consider using methods to get the sub-Objects The advantage would be that the objecs are not initialized until they are need it, and also provides a much more loosely coupled code that lets you change the way the database is initialized more easy.

class Chesterx{ public $database, $member; public function getDatabase() { if (!$this->database ) { $this->database = new database; //Whatever you use to create a database } return $this->database; } public function getMember() { if (!$this->member) { $this->member = new member; } return $this->member; }

}

Recommend