[英]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::testPrivate
和Foo::testPublic
我以為它將打印Foo::testPrivate
和Foo::testPublic
只能從與其定義相同的類中訪問private
方法或屬性Bar::testPrivate
僅可以從Bar
調用,這就是private
意思。 相反,只能從Foo
類定義內的代碼中調用Foo::testPrivate
。
由於Bar::test
在Bar
,因此無法調用Foo::testPrivate
。 它可以調用的唯一實現是Bar::testPrivate
。 但是public
方法沒有這種限制,子類的重寫方法被調用。
如果您覆蓋Foo
的test
方法,則情況將相反:
class Foo extends Bar {
public function test() {
$this->testPrivate();
$this->testPublic();
}
...
}
現在,代碼實際上位於Foo
並且只能調用Foo::testPrivate
。
私有=對此類創建的對象可見,而對於外部世界則不可見
受保護=對所有類和從該類繼承的對象可見,但對外部世界不可見(您要查找的內容)
公眾=隨處可見
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.