note 68028 added to language.oop5.decon

From: Date: Mon, 10 Jul 2006 21:18:49 +0000
Subject: note 68028 added to language.oop5.decon
Groups: php.notes 
Request: Send a blank email to php-notes+get-114644@lists.php.net to get a copy of this message
Peter has suggested using static methods to compensate for unavailability of multiple constructors in PHP. This works fine for most purposes, but if you have a class hierarchy and want to delegate parts of initialization to the parent class, you can no longer use this scheme. It is because unlike constructors, in a static method you need to do the instantiation yourself. So if you call the parent static method, you will get an object of parent type which you can't continue to initialize with derived class fields. Imagine you have an Employee class and a derived HourlyEmployee class and you want to be able to construct these objects out of some XML input too. <?php class Employee { public function __construct($inName) { $this->name = $inName; } public static function constructFromDom($inDom) { $name = $inDom->name; return new Employee($name); } private $name; } class HourlyEmployee extends Employee { public function __construct($inName, $inHourlyRate) { parent::__construct($inName); $this->hourlyRate = $inHourlyRate; } public static function constructFromDom($inDom) { // can't call parent::constructFromDom($inDom) // need to do all the work here again $name = $inDom->name; // increased coupling $hourlyRate = $inDom->hourlyrate; return new EmployeeHourly($name, $hourlyRate); } private $hourlyRate; } ?> The only solution is to merge the two constructors in one by adding an optional $inDom parameter to every constructor. ---- Server IP: 66.163.161.117 Probable Submitter: 128.227.27.98 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.decon.php Edit -- http://master.php.net/note/edit/68028 Del: integrated -- http://master.php.net/note/delete/68028/integrated Del: useless -- http://master.php.net/note/delete/68028/useless Del: bad code -- http://master.php.net/note/delete/68028/bad+code Del: spam -- http://master.php.net/note/delete/68028/spam Del: non-english -- http://master.php.net/note/delete/68028/non-english Del: in docs -- http://master.php.net/note/delete/68028/in+docs Del: other reasons-- http://master.php.net/note/delete/68028 Reject -- http://master.php.net/note/reject/68028 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#114644) next »