![](/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.