简体   繁体   中英

PHP object-oriented Inheritance - accessing parent's property

I need to access a property of a parent inside a function of the child class. A static variable can accessed with parent:: but how can I access a non-static parent variable when the child class has a variable with the same name?

class My_parent{
  $name = "Praeep";
}

class My_child extends My_parent {
  $name ="Nadeesha";

  function show_name() {
    // need to access $name of the parent just referring the parent variable 
  }
}

You can either declare the variable in the parent class with a protected modifier or provide a getter. The getter approach would be prefered to ensure encapsulation.

class My_parent{
  private $name = "Praeep";
  public function getName() {
      return $this->name;
  }
}

class My_child extends My_parent {
  public function show_name() {
    echo $this->getName(); 
  }
} 

If you also want the property to be mutable consider providing a setter as well.

Add a construct function to your parent class and define your variable inside this function.

class My_parent{
  public $name;
  public function __construct(){
    $this->name= "Praeep";
  }
}

If your child class has a construct function too, you need to invoke the parents construct function manually. However a class doesn't have to have a construct function so I commented it out for simplicity.

class My_child extends My_parent {
  // public function __construct(){
  //   parent::__construct();
  // }
  public function show_name(){
    echo $this->name;
  }
}

$c=new My_child();
$c->show_name();

EDIT:

well in fact you don't need the construct function in the parent class.

class My_parent{
  public $name= "Praeep";
}

class My_child extends My_parent {

  public function show_name(){
    echo $this->name;
  }
}

$c=new My_child();
$c->show_name();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM