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

  • 4
    You can only call the protected method from inside the child class, not top-level code. – Barmar Aug 30 '23 at 17:46
  • Here's some documentation to read: https://www.php.net/manual/en/language.oop5.visibility.php. "Members declared protected can be accessed only within the class itself and by inheriting and parent classes. Members declared as private may only be accessed by the class that defines the member." – Devon Bessemer Aug 30 '23 at 17:47
  • Method and property access control is based on where the call is written, not the type of the object. – Barmar Aug 30 '23 at 17:47
  • I didn't catch that ! would you please take an example like mine? also I added a picture on my question. https://stackoverflow.com/users/1491895/barmar – shahriar Aug 30 '23 at 18:08
  • If you could call a protected method from the outside, what would be the difference with a public method? – Olivier Aug 30 '23 at 18:10
  • In your picture, the cell "Protected / Outside class" is in red. – Olivier Aug 30 '23 at 18:13
  • it's not just outside! it's inheritance!! https://stackoverflow.com/users/12763954/olivier – shahriar Aug 30 '23 at 18:13
  • 1
    `$obj->protected_message();` is a call from outside. – Olivier Aug 30 '23 at 18:13
  • would you please edit my code in a way the protected method works?https://stackoverflow.com/users/12763954/olivier – shahriar Aug 30 '23 at 18:16
  • https://stackoverflow.com/questions/32529378/how-to-call-a-protected-method-in-php – Nigel Ren Aug 30 '23 at 18:19

1 Answers1

1

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();
Olivier
  • 13,283
  • 1
  • 8
  • 24