note 104294 deleted from language.oop5.visibility by danbrown
| From: | danbrown@php.net | Date: | Mon, 06 Jun 2011 16:15:34 +0000 |
| Subject: | note 104294 deleted from language.oop5.visibility by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-180304@lists.php.net to get a copy of this message | ||
Note Submitter: seainmalkin at gmail dot com
----
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"
?>