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();

详细代码如上,代码编写没有问题,但是就是执行不了,提示Call to undefined function doIt(),不知道怎么回事。

阅读 2.6k
4 个回答

php 实例化类的方法调用用->表示, $fb.doIt() ;这种写法不能指定对应方法,会将类和方法分离: $fb 是对象,因为此处echo了,所以会先调用魔术方法 __toString() ,然后后面的 doIt() 被识别成函数,而此处未定义函数,所以会提示 Call to undefined function doIt() 。
不然你试试看在类中定义 __toString() 魔术方法并在类外 定义一个函数,函数名为 doIt(),此时 $fb.doIt() 就相当于获取到一个字符串。good luck~

$fb->doIt();

新手上路,请多包涵

额。。。求大神解释。可以像提问说的那样 $fb.doIt() 这样来调用方法名?

你好,php里面调用类的方法有两种
1)$obj->function()
2)$obj::function() 这个要将方法定义为静态方法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题