माता पिता :: विधि केवल माता-पिता के तरीकों है कि आप अपने उपवर्ग में अधिरोहित किया है, या जैसे स्थैतिक चर का उपयोग किया जाता है। बेस क्लास के कन्स्ट्रक्टर में सबक्लास नहीं बनाएं, जो ओओपी सर्वोत्तम प्रथाओं को उल्टा (ढीला युग्मन, इत्यादि) के सभी प्रकारों को एक अनंत लूप बनाते समय बदल देता है। (नया ContactInformation() उपयोगकर्ता नाम कन्स्ट्रक्टर को कॉल करता है जो एक नया ContactInformation() बनाता है जो ...)।
आप एक उपवर्ग, कुछ इस तरह करना चाहते हैं:
/**
* 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
}
}
या आप एक प्रतिनिधि इस्तेमाल कर सकते हैं, लेकिन फिर ContactInformation तरीकों प्रयोक्ता नाम गुण के लिए सीधी पहुँच नहीं होगा।
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
}
}
स्रोत
2009-05-06 21:05:14
मैं तुम्हें कक्षा विस्तार और खरोंच से अमूर्त पढ़ने की जरूरत है लगता है। – OIS
"निजी __construct" uff। –