phpoopinheritanceprotected

OOP in PHP - Inheritance - protected method error


//((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


Solution

  • 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();