$this->a->b->c->d calling methods from a superclas

2019-06-03 22:57发布

问题:

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

回答1:

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


回答2:

Consider the Singleton pattern - it usually fits better for database interactions. http://en.wikipedia.org/wiki/Singleton_pattern.



回答3:

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

}



标签: php oop