![](/img/trans.png)
[英]How to use $this->methodname in PHP session_set_save_handle?
[英]how to make parent method to be called using $this->methodName in PHP?
我有两节课。 一个是父母,另一个是孩子。 两者都有相同的命名方法。 问题是父方法不会使用$ this-> methodName调用。
家长班
class Parent
{
public function __construct()
{
$this->init();
}
// this function never get executed and why?
public function init()
{
//do something
}
}
儿童班
class Child extends Parent
{
public function __construct()
{
parent::__construct();
$this->init();
}
public function init()
{
// do something different
}
}
如何在不使用parent :: init的情况下调用父方法?
您可以使用self
来引用当前类。 与$this
相对,后者在运行时引用当前对象。
class ParentClass
{
public function __construct()
{
self::init();
}
public function init()
{
echo 'parent<br/>';
}
}
<?php
public function __construct(){
parent::__construct();
self::init();
}
?>
父类中的其他对象还使用self来避免执行父init和子init。
事情是parent::
是有原因的,其中一个原因是要处理您遇到的“问题”(这不是问题)。
显然,如果您的子类具有例如myfunction()
的功能,而父类具有名为myfunction()
的功能,则如果在$this->myfunction()
使用$this->myfunction()
,则显然会调用子代的myfunction()
函数因为$this
是对当前对象的引用。
使用parent
没有任何危害,这是有原因的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.