0

我不明白为什么代码的第一个输出会打印“Bar::testPrivate”,因为我们正在使用子类的实例调用父类的测试方法。所以,当调用测试函数中的第一行代码时,它是“$this->testPrivate();” 应该调用子类的 testPrivate 方法,因此打印“Foo::testPrivate”而不是“Bar::testPrivate”。

<pre>
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



</pre>
4

2 回答 2

1

如果您希望从基(父)类继承所有函数,那么您应该在子类中显式调用它的构造函数。否则,您将需要覆盖这些方法。此外,当使用实际实例(即您创建了一个对象)时,声明的函数private仅对该类可用。用于protected将继承该函数的类。例如:

class Foo {

    public function __construct() {
        echo "Foo constructed...\n";
        $this->fooOnly();
    }

    private function fooOnly() {
        echo "Called 'fooOnly()'\n";  //Only available to class Foo
    }

    protected function useThisFoo() {
        echo "Called 'useThisFoo()'\n";  //Available to Foo and anything that extends it.
    }

}

class Bar extends Foo {

    public function __construct() {
        parent::__construct();  //Now Bar has everything from Foo
    }

    public function testFooBar() {
        //$this->fooOnly(); //Fail - private function
        $this->useThisFoo(); //Will work - protected function is available to Foo and Bar
    }

}

$bar = new Bar();
$bar->testFooBar();  //Works - public function will internally call protected function.
//$bar->fooOnly();  //Fail - private function can't be accessed in global space
//$bar->useThisFoo();  //Fail again - protected function can't be access in global space
于 2013-10-31T01:16:34.677 回答
1

你的类Foo没有test()方法。您可以调用$myFoo->test(),因为该方法test()是从 class 继承的Bar。您必须像使用test()方法和.FootestPrivate()testPublic()

您是正确的,它正在调用基类的方法,但在这种情况下Bar是您的基类。在此处查看示例。

于 2013-10-31T01:04:29.570 回答