PHP Objects (Inheritance Problem)
Posted: Sun Jun 14, 2009 4:31 pm
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.
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:
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:
Any ideas at all would be great? 
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);
}
}
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 code in the global scope is:
Code: Select all
$system = new System();
$user = new User();
$user->set_user('Root');
echo $system->session->username;