簡體   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