0

I understand that I should make a method "protected" when I want it to be only available to all classes that extend the current class as well as the current class.

Okay, grandChildClass::method2() should be protected since grandchild is extended from child.

But what should it be if accessed from a parent class such as parentClass::method2()?

class parentClass
{
    public function method1() {$this->method2();}
}

class childClass extends parentClass
{
    protected function method2() {}
}

class grandChildClass extends childClass 
{
    public function method3() {$this->method2();}
}
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • but if you wish call method that was not extended then you need to use this solution :: https://stackoverflow.com/questions/17174139/can-i-how-to-call-a-protected-function-outside-of-a-class-in-php/70462175#70462175 – pankaj Dec 23 '21 at 12:34

1 Answers1

2

If you try to

$p = new parentClass;
$p->method1();

You'd get a fatal error for undefined method.

Fatal error: Call to undefined method parentClass::method2() in ... on line ...

However, this will work fine:

$c = new childClass;
$c->method1();

$g = new grandChildClass;
$g->method1();
$g->method3();

All of these will call method2 as defined on childClass.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • To make this cleaner the `parentClass` could define a pure virtual version of `method2` as follows `virtual method2() = 0;`. This would explicitly require any childClass to implement a `method2()` function so that it could be called my methods of the `parentClass`. – Alan Apr 13 '13 at 21:33
  • Thanks, I was hoping it worked just as you state! I confused myself, and was accessing a method defined in my parentClass, but from within the grandchildClass, so obviously the childClass method worked just fine. – user1032531 Apr 13 '13 at 21:38
  • @Alan: There are no `virtual` methods in PHP. You can define a class and its methods as `abstract` (which means they have only definition and can't be instantiated). – Madara's Ghost Apr 13 '13 at 21:58
  • Thanks @MadaraUchiha, that's what I meant, define it as abstract. I got my C++ and PHP mixed up. – Alan Apr 14 '13 at 15:12
  • Another way to do something like this :: https://stackoverflow.com/questions/17174139/can-i-how-to-call-a-protected-function-outside-of-a-class-in-php/70462175#70462175 – pankaj Dec 23 '21 at 12:37