鍍金池/ 問答/PHP/ Call to undefined function doIt()

Call to undefined function doIt()

class Ball{
    const SHAPE = "circular";
    public $area = null;
}

class Football extends Ball{
    const PI = 3.14;
    public $radius;

    public function __construct($radius){
        $this->radius = $radius;
    }

    public function doIt(){
        $this->area = PI*pow($this->radius,2);
        return "the shape of the ball is:".self::SHAPE."the area is:".$this->area;
    }
}

$fb = new Football(2.15);
echo $fb.doIt();

詳細(xì)代碼如上,代碼編寫沒有問題,但是就是執(zhí)行不了,提示Call to undefined function doIt(),不知道怎么回事。

回答
編輯回答
忘了我

$fb->doIt();

2017年10月27日 18:50
編輯回答
菊外人

php 實例化類的方法調(diào)用用->表示, $fb.doIt() ;這種寫法不能指定對應(yīng)方法,會將類和方法分離: $fb 是對象,因為此處echo了,所以會先調(diào)用魔術(shù)方法 __toString() ,然后后面的 doIt() 被識別成函數(shù),而此處未定義函數(shù),所以會提示 Call to undefined function doIt() 。
不然你試試看在類中定義 __toString() 魔術(shù)方法并在類外 定義一個函數(shù),函數(shù)名為 doIt(),此時 $fb.doIt() 就相當(dāng)于獲取到一個字符串。good luck~

2017年4月14日 05:24
編輯回答
骨殘心

你好,php里面調(diào)用類的方法有兩種
1)$obj->function()
2)$obj::function() 這個要將方法定義為靜態(tài)方法

2018年2月26日 15:56
編輯回答
乖乖噠

額。。。求大神解釋??梢韵裉釂栒f的那樣 $fb.doIt() 這樣來調(diào)用方法名?

2017年12月27日 13:01