Sercan VİRLAN
Sercan VİRLAN

Reputation: 123

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

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

Upvotes: 1

Views: 755

Answers (3)

Gabriel Solomon
Gabriel Solomon

Reputation: 30105

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

}

Upvotes: 0

Alex Weinstein
Alex Weinstein

Reputation: 9891

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

Upvotes: 1

Pim Jager
Pim Jager

Reputation: 32129

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

Upvotes: 2

Related Questions