繁体   English   中英

PHP 代码。 $this->published = true 如何调用文章方法

[英]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名称相同。
如果类Classnamemethod name相同,则method name被视为constructor

您可以放置一个空白的__construct()方法来避免它。 像这样:

<?php
class Article extends Content
{
    function __construct(){
        //code
    }
    
    public function article()
    {
        echo "<i>Post:</i>";
    }
}

php 构造函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM