Parent :: yöntem size sadece alt sınıfta veya benzeri statik değişkenleri geçersiz kılınmış ana yöntemlerine erişmek için kullanılır:
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"
Muhtemelen uygun bir alt sınıfı istiyorum. Ayrıca sonsuz bir döngü oluştururken temel sınıfın yapıcısı bir alt sınıfı oluşturmak etmeyin, bu baş aşağı (gevşek bağlanması, vb) OOP en iyi uygulamaları her türlü döner. (Yeni İletişim Bilgileri () yeni bir İletişim Bilgileri () oluşturur adı kurucu çağırır ...).
: Bir alt sınıfı, böyle bir şey istiyorum
/**
* 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
}
}
Ya da bir temsilci kullanabilirsiniz, ancak daha sonra İletişim Bilgileri yöntemleri Kullanıcı Adı özelliklerine doğrudan erişim olmazdı.
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
}
}