" . "from Parent class ."; } protected" /> " . "from Parent class ."; } protected" /> " . "from Parent class ."; } protected"/>

OOP in PHP - Inheritance - protected method error

43 Views Asked by At
//((inheritance))

class ParentClass
{
    public function public_message()
    {
        echo "This is a Public message" . "<br>" . "from Parent class .";
    }

    protected function protected_message()
    {
        echo "This is a Protected message" . "<br>" . "from Parent class .";
    }
}


class Child extends ParentClass
{
}

$obj = new Child();
$obj->protected_message();

I got an error ! but as we know , protected methods ( or properties ) can also use correctly in inheritance.

enter image description here

1

There are 1 best solutions below

0
Olivier On BEST ANSWER

Here is an example which shows a valid call to the protected method:

class ParentClass
{
    public function public_message()
    {
        echo "This is a Public message" . "<br>" . "from Parent class .";
    }

    protected function protected_message()
    {
        echo "This is a Protected message" . "<br>" . "from Parent class .";
    }
}


class Child extends ParentClass
{
    public function test()
    {
        $this->protected_message();
    }
}

$obj = new Child();
$obj->test();