What’s a more correct way to call a parent classes functions? parent:: or $this-> ?
class base{
public function get_x(){
return 'x';
}
}
class child extends base{
public function __construct(){
//this?
$x = parent::get_x();
//or this?
$x = $this->get_x();
}
}
Thanks!
There is no “more correct” synthax because they have their own sense.
$this->means “the current object”, so if a method is overriden, this is that method you would call.parent::means “the parent’s behaviour”. It is useful when you override a methode and you want to add something to parent’s behaviour.So, if somewhere in your class
childyou override the get_x method and you want the parent’s behaviour only, use parent:: if not, use $this.I would make an end to this answer by saying it is often advised not to call a not final method in a constructor as anyone can redefine the behaviour by extending it.