Die parent :: Methode wird nur für den Zugriff auf übergeordnete Methoden verwendet, die Sie in Ihrer Unterklasse außer Kraft gesetzt haben, oder statische Variablen wie:
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"
Sie wahrscheinlich eine richtige Unterklasse will. Erstellen Sie im Konstruktor der Basisklasse keine Unterklasse, die alle Arten von OOP-Best Practices auf den Kopf stellt (lose Kopplung usw.) und gleichzeitig eine Endlosschleife erstellt. (new ContactInformation() ruft den Username-Konstruktor auf, der eine neue ContactInformation() erstellt, die ...).
Wenn Sie eine Unterklasse, etwa wie folgt:
/**
* 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
}
}
Oder Sie könnten einen Delegaten verwenden, aber dann würden die Contact Methoden haben keinen direkten Zugriff auf den Benutzername Eigenschaften.
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
}
}
Ich glaube, Sie brauchen Klassenerweiterung und Abstraktion von Grund auf neu zu lesen. – OIS
"private __construct" uff. –