note 104294 added to language.oop5.visibility

From: Date: Mon, 06 Jun 2011 15:27:18 +0000
Subject: note 104294 added to language.oop5.visibility
Groups: php.notes 
Request: Send a blank email to php-notes+get-180303@lists.php.net to get a copy of this message
reference to - ryan dot m dot lange at gmail dot com The output of ChildClass2::foo() and ChildClass2::bar() is expected. You can't access a private property of a parent class. In the example below, ChildClass2 assigns a value to a property with the same name as the parents private property. Though it's not accessing the parents property, but creating a new public property belonging to ChildClass2. <?php class ParentClass { private $foo; public function __construct() { $this->foo = 'foo'; } public function foo() { echo $this->foo; } } class ChildClass1 extends ParentClass { public function bar() { echo $this->foo; } } class ChildClass2 extends ParentClass { public function __construct() { // this isn't overriding the parents private property // but is creating a new public property belonging to this class $this->foo = 'bar'; } public function bar() { // echos the property created in the constructor and // not the private property with the same name in the parent class echo $this->foo; } } $parent = new ParentClass(); $parent->foo(); // "foo" $child1 = new ChildClass1(); $child1->foo(); // "foo" $child1->bar(); // "Notice: Undefined property: ChildClass1::$foo in [file] on line [line]" $child2 = new ChildClass2(); $child2->foo(); // <nothing> >> because the parents property has not yet been set. The parents constructor method won't be executed unless called by the child $child2->bar(); // "bar" >> method is not accessing the parents property, but its own created in the constructor // you can test this by accessing the property directly echo $child2->foo // "bar" ?> ---- Server IP: 69.147.83.197 Probable Submitter: 180.216.19.85 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.visibility.php Edit -- https://master.php.net/note/edit/104294 Del: integrated -- https://master.php.net/note/delete/104294/integrated Del: useless -- https://master.php.net/note/delete/104294/useless Del: bad code -- https://master.php.net/note/delete/104294/bad+code Del: spam -- https://master.php.net/note/delete/104294/spam Del: non-english -- https://master.php.net/note/delete/104294/non-english Del: in docs -- https://master.php.net/note/delete/104294/in+docs Del: other reasons-- https://master.php.net/note/delete/104294 Reject -- https://master.php.net/note/reject/104294 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#180303) next »