![](/img/trans.png)
[英]how to make parent method to be called using $this->methodName in PHP?
[英]PHP code. How $this->published = true called the article method
<?php
class Content
{
public function publish()
{
$this->published = true;
$this->article();
}
protected function article()
{
echo "<i>Article:</i>";
}
}
class Article extends Content
{
public function article()
{
echo "<i>Post:</i>";
}
}
$post = new Article();
$post->publish();
/*
Code Output : <i>Post:</i><i>Post:</i>
*/
?>
這段代碼調用了 article 方法兩次。 當我調用發布方法時。 我不明白這段代碼。 $this->published = true 是如何調用 article 方法的。 哪個看起來甚至不像是財產?
因為您將article()
方法的名稱定義為與 class Article
名稱相同。
如果類Classname
和method name
相同,則method name
被視為constructor
您可以放置一個空白的__construct()
方法來避免它。 像這樣:
<?php
class Article extends Content
{
function __construct(){
//code
}
public function article()
{
echo "<i>Post:</i>";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.