簡體   English   中英

php oop可見性:父類中的函數如何調用其自身的私有函數和子類的公共函數

[英]php oop visibility: How the function in parent class calls it's own private function and child class public function

我不知道如何問這個問題,這就是為什么標題沒有的原因。 好,如果有人可以請更改它。

它位於方法可見性下的PHP文檔http://php.net/manual/zh/language.oop5.visibility.php中。

<?php

class Bar 
{
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublic\n";
    }

    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}

class Foo extends Bar 
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }

    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}

$myFoo = new Foo();
$myFoo->test(); // Bar::testPrivate 
                // Foo::testPublic
?>

在上面的代碼中, $myFoo->test()如何打印Bar::testPrivateFoo::testPublic我以為它將打印Foo::testPrivateFoo::testPublic

只能從與其定義相同的類中訪問private方法或屬性Bar::testPrivate僅可以從Bar調用,這就是private意思。 相反,只能從Foo類定義內的代碼中調用Foo::testPrivate

由於Bar::testBar ,因此無法調用Foo::testPrivate 它可以調用的唯一實現是Bar::testPrivate 但是public方法沒有這種限制,子類的重寫方法被調用。

如果您覆蓋Footest方法,則情況將相反:

class Foo extends Bar {
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    ...
}

現在,代碼實際上位於Foo並且只能調用Foo::testPrivate

私有=對此類創建的對象可見,而對於外部世界則不可見

受保護=對所有類和從該類繼承的對象可見,但對外部世界不可見(您要查找的內容)

公眾=隨處可見

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM