为什么调用 Foo class 的 test() 函数(它扩展了 Bar class)returns 的结果来自两个 classes?

Why does calling of test() function of Foo class (which extends Bar class) returns result mixed from both classes?

这听起来可能很傻,但我是 PHP 的新手。当我来到这个部分时,我正在从有关访问说明符的文档中学习。

class Bar {
    public function __construct() {
        echo "Bar::constructor<br />";
    }
    public function test() {
        $this->PublicTest();
        $this->PrivateTest();
        $this->protectedTest();
    }
    public function PublicTest(){
        echo "Bar::testPublic<br />";
    }
    private function PrivateTest() {
        echo "Bar::testPrivate<br />";
    }
    protected function ProtectedTest() {
        echo "Bar::testProtected<br />";
    }
}

class Foo extends Bar {
    public function __construct() {
        echo "Foo::constructor<br />";
    }
    public function PublicTest() {
        echo "Foo::testPublic<br />";
    }
    private function PrivateTest() {
        echo "Foo::testPrivate<br />";
    }
    protected function ProtectedTest() {
        echo "Foo::testProtected<br />";
    }
}

$myFoo = new Foo();
$myFoo->test();

?>

这会产生如下输出:

Foo::constructor
Foo::testPublic
Bar::testPrivate
Foo::testProtected

为什么 private 函数从 Bar class 打印,而 public 和 [=] 从 Foo class 打印19=]函数?因为,我在 Foo class 中没有 test() 函数,它从 Bar class.[=27= 访问 test() 函数]

$this指针指向哪里?是指向Fooclass的函数还是Barclass的函数?我真的很困惑。有人可以向我解释一下吗?非常感谢任何帮助。

$this 是当前对象....也许 self::PublicTest();当您制作 new Foo(); 时会产生您认为应该产生的结果; $this-> 指的是您创建的当前对象,而不是当前的 class –

class Animal {

     public function whichClass() {
        echo "I am an Animal!";
    }

   /* This method has been changed to use the 
       self keyword instead of $this
   */

    public function sayClassName() {
       self::whichClass();
    }

}

class Tiger extends Animal {

    public function whichClass() {
        echo "I am a Tiger!";
    }

}

$tigerObj = new Tiger();
$tigerObj->sayClassName();

这将产生我是动物!

这取自 http://www.programmerinterview.com

这是因为每个 class/function 的可见性。 当我们首先调用 test() 时,使用这个:

$myFoo = new Foo();
$myFoo->test();

我们在 Bar class 中调用 test(),因为 Foo 扩展了 Bar 并且它使用 Bar 的 test() 因为它是 public 并且在 class Foo 中可见。 现在,在 Barclass 的 foo() 中,调用了这 3 个函数:

$this->PublicTest();
$this->PrivateTest();
$this->protectedTest();

在这里,我们现在在 Bar class 内,因此它只能看到它自己的 class 的 PrivateTest() 和 ProtectedTest()。因为这些函数的可见性设置为PrivateProtected。 但是在 PublicTest() 的情况下,它可以看到 2 个函数。因为 PublicTest() 设置为 Public FooBar[=] 可见性38=] class。 此处,Public Bar class 的函数被选中,尽管 Foo class 有自己的 PublicTest() 因为以下原因:

因为,我们正在使用 $this 处理程序,它总是引用当前正在使用的对象(属于 Foo class 在这种情况下),它选择 PublicTest() of Foo class.