简体   繁体   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>
*/

  
?>

This code called the article method twice.这段代码调用了 article 方法两次。 when i called the publish method.当我调用发布方法时。 I don't understand this code.我不明白这段代码。 How $this->publised = true called the article method. $this->published = true 是如何调用 article 方法的。 which does not look like even a property?哪个看起来甚至不像是财产?

Because you define the name of article() method as same as the the class Article name.因为您将article()方法的名称定义为与 class Article名称相同。
If both Classname and method name are same, then the method name will be treated as constructor如果类Classnamemethod name相同,则method name被视为constructor

You can put a blank __construct() method to avoid it.您可以放置一个空白的__construct()方法来避免它。 Just like this:像这样:

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

php Constructors php 构造函数

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

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