0

サブクラスのインスタンスを使用して親クラスのテストメソッドを呼び出しているため、コードの最初の出力が「Bar::testPrivate」を出力する理由がわかりませんでした。したがって、テスト関数内のコードの最初の行を呼び出すと、 「$this->testPrivate();」サブクラスの testPrivate メソッドを呼び出す必要があるため、「Bar::testPrivate」ではなく「Foo::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

あなたのクラスにはメソッドFooがありませんtest()$myFoo->test()メソッドtest()は class から継承されているため、呼び出すことができますBar。メソッドと. test()_ _FootestPrivate()testPublic()

基本クラスのメソッドを呼び出しているのは正しいですが、この場合Barは基本クラスです。こちらの例をご覧ください。

于 2013-10-31T01:04:29.570 に答える
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 に答える