PHP - Rewrite protected method in extended class

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts: 62

PHP - Rewrite protected method in extended class

Hello
Is it possible to rewrite /replace a protected method in the extended class, in php?

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 

Similar Topics