note 109702 added to language.oop5.inheritance

From: Date: Sat, 11 Aug 2012 18:02:21 +0000
Subject: note 109702 added to language.oop5.inheritance
Groups: php.notes 
Request: Send a blank email to php-notes+get-190038@lists.php.net to get a copy of this message
I don't know (and remember) if it's stated in the documentation but I thought were worth to post this note in Object Inheritance instead of in "Constructors and Destructors". This note talks about inheritance and constructors (and maybe destructors? I haven't checked yet). Assuming that you have two classes, the second inherits from the first: Class-1.php <?php class First_Class { protected $_bar = "PHP Rocks!"; public function __construct($mandatoryArg) { echo "Here is the mandatory argument: $mandatoryArg"; } // Other methods.. } ?> Class-2.php <?php class Second_Class extends First_Class { public function foo() { echo "Method foo() fired! " . $this->_bar; } } ?> Now, if you then need to use the second class BUT this method make use of a property coming from the First_Class, so you then write: index.php <?php include 'First-Class.class.php'; include 'Second-Class.class.php'; $second = new Second_Class; $second->foo(); ?> PHP will raise an error because by instantiating the Second_Class that extends the First_Class THAT HAVE a constructor WITH a $mandatoryArg setted...it doesn't find this argument. So here the error. Solution: in the Second_Class that extends the First_Class add an 'empty __construct'. Example: <?php class Second_Class extends First_Class { public function __construct() { return; } // Same as above.. } ?> I'm opened to clarifications because today I've discovered this behaviour for the first time (+4 years PHP development). Hope it will helps. Kind regards. W.D. ---- Server IP: 69.147.83.197 Probable Submitter: 2.227.252.36 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.inheritance.php Edit -- https://master.php.net/note/edit/109702 Del: integrated -- https://master.php.net/note/delete/109702/integrated Del: useless -- https://master.php.net/note/delete/109702/useless Del: bad code -- https://master.php.net/note/delete/109702/bad+code Del: spam -- https://master.php.net/note/delete/109702/spam Del: non-english -- https://master.php.net/note/delete/109702/non-english Del: in docs -- https://master.php.net/note/delete/109702/in+docs Del: other reasons-- https://master.php.net/note/delete/109702 Reject -- https://master.php.net/note/reject/109702 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#190038) next »