Page 1 of 1

PHP Objects (Inheritance Problem)

Posted: Sun Jun 14, 2009 4:31 pm
by AlanG
Just a question, I am curious about. I have solved this problem already but I think it's a messy solution and would like to remedy it if possible.

Code: Select all

 
class Session
{
   public $username;
 
   public function set_username($username)
   {
      $this->username = $username;
      $_SESSION['username'] = $username;
   }
}
 
class System
{
   public $database;
   public $session;
 
   public function __construct()
   {
      $this->database = new Database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
      $this->session = new Session();
   }
}
 
class User extends System
{
   public $username;
 
   public function set_user($username)
   {
      $this->username = $username;
      $this->session->set_username($username);
   }
}
 
The problem I am having is that in the User class, the Session class does not appear to be being called. Is it being passed by value? If it was that would make sense, but in PHP 5, all objects are passed by reference, which would make this peculiar. No errors are returned, it's just whitespace.

My messy solution is:

Code: Select all

 
class User
{
   public $database;
   public $session;
 
   public $username;
 
   public function __construct()
   {
      global $system;
    
      $this->database = $system->database;
      $this->session = $system->session;
   }
 
   public function set_user($username)
   {
      $this->username = $username;
      $this->session->set_username($username);
   }
}
 
The above User class works fine but I'm not happy with it. Maybe it's the right way to go, but if there is a better way, i'd like to find it.

The code in the global scope is:

Code: Select all

 
$system = new System();
 
$user = new User();
$user->set_user('Root');
 
echo $system->session->username;
 
Any ideas at all would be great? :)

Re: PHP Objects (Inheritance Problem)

Posted: Mon Jun 15, 2009 2:47 am
by miro_igov
You forgot to call parent::__construct() in child class constructor.

Re: PHP Objects (Inheritance Problem)

Posted: Mon Jun 15, 2009 10:36 am
by AlanG
miro_igov wrote:You forgot to call parent::__construct() in child class constructor.
I have called it. These are only partial classes (they would take up a few pages otherwise). In the first code segment, the user class extends the system class. I have called parent::__construct(); in the user class here. In the second segment, I have rewritten the user class, removing the inheritance and bridging it to the other classes through the global scope. When i introduce the global variables, the system works perfectly, but I would like to do it without calling variables in the global scope.