2009-12-27 90 views
0

如何使用我在子類中的父類中定義的函數?Php繼承問題

例如,如果我使用一個類像下面

<?php 

class mat 

{ 

function square($x) 

{ 

return $x *$x; 

} 

} 


class matchild extends mat 

{ 

function doublesquare($x) 
{ 

return square($x) * square($x) 

} 

} 

?> 

如果我嘗試上面,我得到一個錯誤說,廣場的功能是沒有定義。

解答和建議表示讚賞。

回答

10

您需要使用this

return $this->square(x) * $this->square(x); 

檢查出類和對象PHP的basic documentation

+0

感謝,我會在手動 – jimbo 2009-12-27 07:24:35

-2

在matchild的構造器調用parent::__construct()

class matchild extends mat 
{ 
    function __construct() 
    { 
     parent::__construct(); 
    } 
} 

然後就可以調用包含在父內的任何方法與$this->

+2

你並不需要調用父類的構造函數來使用它的方法看看。 – 2009-12-27 07:18:06

+0

你是對的。這些年來一直做錯了。 :) – 2009-12-28 04:43:51

1

與段夫婦的問題。但是,你要尋找的答案是:

$this->square() 
0

parent::square(x) * parent::square(x)