Page 1 of 1

PHP - Rewrite protected method in extended class

Posted: 20 Nov 2015, 08:28
by Marius
Hello
Is it possible to rewrite /replace a protected method in the extended class, in php?

PHP - Rewrite protected method in extended class

Posted: 20 Nov 2015, 08:31
by Admin
Hello
Yes, you can change the protected attribute of the method in the extended class:

Code: Select all

class A {
  protected function f1(){
    return 'abc';
  }
}

class B extends A {
  public function f1(){
    return 'xyz';
  }
}

$ob =  new B;
echo $ob->f1();  // xyz 
In the same way, you can rewrite the protected method, maintaining the same attribute:

Code: Select all

class A {
  protected function f1(){
    return 'abc';
  }
}

class B extends A {
  protected function f1(){
    return 'xyz';
  }

  public function f2(){
    return 123 . $this->f1();
  }
}

$ob =  new B;
echo $ob->f2();  // 123xyz