问题
Say I have class child()
and class parent()
. The parent has a constructor and a few other public methods, and the child is empty apart from a constructor.
How do I go about calling a parent's methods inside of the child's constructor, as in:
Class Parent {
public function __construct() {
// Do stuff (set up a db connection, for example)
}
public function run($someArgument) {
// Manipulation
return $modifiedArgument;
}
}
Class Child extends Parent {
public function __construct() {
// Access parent methods here?
}
}
Say I want to call parent
s run()
method, do I have to call a new instance of the parent inside the child constructor? Like so...
$var = new Parent();
$var->run($someArgument);
If so, what is the point of extends
from a class definition POV? I can call a new instance of another class with the new
keyword whether it extends the 'child' or not.
My (likely) wrong understanding was that by using extends
you can link classes and methods from a parent can be inherited into the child. Is that only outside the class definition? Does using extend
offer no efficiencies inside the class definition?
Because referring to the parent's run()
method with the this
keyword certainly doesn't work...
回答1:
Use parent
as predefined reference: parent::run()
. This will ensure you call parent method. The same way you could call first parent constructor first or after child one - parent::__construct()
.
Class Child extends Parent {
public function __construct() {
parent::__construct();
// Access parent methods here?
$some_arg = NULL; // init from constructor argument or somewhere else
parent::run($some_arg); // explicitly call parent method
// $this->run($some_arg); // implicitly will call parent if no child override
}
}
If you dont have an implementation in child you could call $this->run($args)
, where it will again call parent run method.
回答2:
To extend Rolice's answer
function a() {
echo 'I exist everywhere';
}
class A {
protected $a
function a() {
$this->a = 'I have been called';
}
function out() {
echo $this->a;
a();
}
}
class B extends A {
function __construct() {
parent::a();// original method
$this->a(); // overridden method
a();
}
function a() {
$this->a = $this->a ? 'I have been overwritten' : 'first call';
}
}
Study these to understand the difference
来源:https://stackoverflow.com/questions/20494518/how-do-i-access-a-parents-methods-inside-a-childs-constructor-in-php