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