The parent:: method is only used to access parent methods that you have overridden in your subclass, or static variables like:
class Base
{
protected static $me;
public function __construct ()
{
self::$me = 'the base';
}
public function who() {
echo self::$me;
}
}
class Child extends Base
{
protected static $me;
public function __construct ()
{
parent::__construct();
self::$me = 'the child extends '.parent::$me;
}
// until PHP 5.3, will need to redeclare this
public function who() {
echo self::$me;
}
}
$objA = new Base;
$objA->who(); // "the base"
$objB = new Child;
$objB->who(); // "the child extends the base"
You probably want a proper subclass. Don't create a subclass in the constructor of the base class, that turns all sorts of OOP best-practices upside down (loose coupling, etc) while also creating an infinite loop. (new ContactInformation() calls the Username constructor which creates a new ContactInformation() which...).
If you want a subclass, something like this:
/**
* Stores basic user information
*/
class User
{
protected $id;
protected $username;
// You could make this protected if you only wanted
// the subclasses to be instantiated
public function __construct ( $id )
{
$this->id = (int)$id; // cast to INT, not string
// probably find the username, right?
}
}
/**
* Access to a user's contact information
*/
class ContactInformation extends User
{
protected $mobile;
protected $email;
protected $nextel;
// We're overriding the constructor...
public function __construct ( $id )
{
// ... so we need to call the parent's
// constructor.
parent::__construct($id);
// fetch the additional contact information
}
}
Or you could use a delegate, but then the ContactInformation methods wouldn't have direct access to the Username properties.
class Username
{
protected $id;
protected $contact_information;
public function __construct($id)
{
$this->id = (int)$id;
$this->contact_information = new ContactInformation($this->id);
}
}
class ContactInformation // no inheritance here!
{
protected $user_id;
protected $mobile;
public function __construct($id)
{
$this->user_id = (int)$id;
// and so on
}
}