note 102287 deleted from language.oop5.visibility by danbrown

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: michal dot php at glomesdal dot com 

----

@ryan dot m dot lange at gmail dot com

The constructor in ChildClass2 overrides the constructor in the parent.  Now, ParentClass must be initialized by calling its constructor explicitly from ChildClass2.

ChildClass2 has no visibility to $foo in the parent so it has locally created its own $foo.  Since it was undeclared, it is a public property.

<?php
class ParentClass
{
    private $foo;

    public function __construct()
    {
        $this->foo = 'foo';
    }

    public function foo()
    {
        echo $this->foo . "\n";
    }
}

class ChildClass2 extends ParentClass
{
    public function __construct()
    {
        $this->foo = 'bar';
        parent::__construct();  // added this line
    }

    public function bar()
    {
        echo $this->foo . "\n";
    }
}

$child2 = new ChildClass2();
$child2->foo(); // now returns "foo"
$child2->bar(); // "bar"
echo $child2->foo; // "bar"

?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.