PHP中的多态性


Polymorphism in PHP

我几周前刚刚学习了PHP,现在我想了解一些PHP中的多态性。我被这样的东西卡住了:

    class A{
    var $n = 0;
    public function f1(){
        $this->n += 4;
        $m = f2();
        return $this->n + $this->m;
    }
    public function f2(){
        $this->n += 1;
        return $this->n;
    }
    public function f3(){
        f1();
        return $this->n;
    }
    class B extends A{
        public function f1(){
            $this->n -= 4;
            $m = f2();
            return $this->n - $this->m;
        }
        public function f2(){
            $this->n += $this->n;
            return $this->n;
        }
    }
    $b = new B();
    $b->n = 4;
    echo $b->f1()." ";
    echo $b->f2()." ";
    echo $b->f3()." ";

它有一个错误:

致命错误:调用未定义的函数f2()

但是,函数f2()是在$m = f2();行中提到的。

这种情况下出了什么问题?谢谢你的帮助!

问题是您没有全局函数f2,您应该使用它这样$this->f2();

如果您还想调用类B的父方法,请尝试parent::f2();,它将调用类A的方法f2()

我希望它能有所帮助。