2013-10-31 32 views
0

我沒有得到爲什麼代碼的第一個輸出打印「Bar :: testPrivate」,因爲我們使用子類的實例調用父類的測試方法。因此,在測試函數中調用「$ this-> testPrivate();」的第一行代碼時,應該調用子類的testPrivate方法,從而打印「Foo :: testPrivate」而不是「Bar :: testPrivate」。請幫我用這個在php.net網站上的代碼

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

回答

1

Foo類沒有一個test()方法。您可以撥打$myFoo->test(),因爲方法test()從類Bar繼承。您必須重寫類Foo中的方法test(),就像您使用方法testPrivate()testPublic()一樣。

你是對的,它調用基類的方法,但在這種情況下,Bar是你的基類。查看示例here

+0

讓我們來看看流程...說$ myFoo-> test();將調用父類的測試方法。現在在測試方法中,第一個語句是$ this-> testPrivate()... $ this在這個上下文中應該引用$ myFoo ...因此我們可以查看調用$ this - > testPrivate()作爲$ myFoo-> testPrivate()...應該調用Foo類的testPrivate()方法... Plz告訴我我要去哪裏錯... – user2939602

+0

我不完全正面它會回到代碼的那一部分,無論是通過堆棧還是通過什麼途徑,但無論哪種方式,您的代碼都在「Bar」類中。因此,任何對「$ this」的引用都是對它實際寫入的任何類的引用。感謝Paulo,對於編輯。 – seemywingz

+0

@seemywingz ..「因此,任何對$ this的引用都是對它實際寫入的任何類的引用」....如果這是真的,那麼調用$ this-> testPublic();通過$ myFoo-> test();應該會導致Bar :: testPublic而不是Foo :: testPublic ...但這不是這種情況...我真的無法得到它... Plz解釋.. – user2939602

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