[英]how to make parent method to be called using $this->methodName in PHP?
I have two classes. 我有两节课。 One is parent and another is child.
一个是父母,另一个是孩子。 Both have a same name method.
两者都有相同的命名方法。 The problem is that parent method does not get called using $this->methodName.
问题是父方法不会使用$ this-> methodName调用。
Parent class 家长班
class Parent
{
public function __construct()
{
$this->init();
}
// this function never get executed and why?
public function init()
{
//do something
}
}
The Child class 儿童班
class Child extends Parent
{
public function __construct()
{
parent::__construct();
$this->init();
}
public function init()
{
// do something different
}
}
How to call the parent method without using parent::init? 如何在不使用parent :: init的情况下调用父方法?
You can use self
to refer to the current class. 您可以使用
self
来引用当前类。 As opposed to $this
, which refers to the current object at runtime. 与
$this
相对,后者在运行时引用当前对象。
class ParentClass
{
public function __construct()
{
self::init();
}
public function init()
{
echo 'parent<br/>';
}
}
<?php
public function __construct(){
parent::__construct();
self::init();
}
?>
Additionaly in Parent class use also self to avoid executing parent init and child init. 父类中的其他对象还使用self来避免执行父init和子init。
The thing is parent::
is there for a reason and one of those reason is to deal with the "problem" (which is not a problem) you have. 事情是
parent::
是有原因的,其中一个原因是要处理您遇到的“问题”(这不是问题)。
Obviously if you have a child class with a function called eg myfunction()
and a parent class with a function called myfunction()
, if you use $this->myfunction()
in the child it will obvious call the child's myfunction()
function because $this
is a reference to the current object. 显然,如果您的子类具有例如
myfunction()
的功能,而父类具有名为myfunction()
的功能,则如果在$this->myfunction()
使用$this->myfunction()
,则显然会调用子代的myfunction()
函数因为$this
是对当前对象的引用。
There is no harm in using parent
, it is there for a reason. 使用
parent
没有任何危害,这是有原因的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.