在php中调用顶级类函数

问题描述 投票:-2回答:1

我有一个场景,在那里,我有三个单独的类文件A.php,B.php,C.php。

A.php是具有一些功能的独立文件,'B'延伸'A','C'延伸'B'。

在'C.php'文件中,我能够访问'B.php'的功能,但不能访问'A.php'的功能。

这是我的结构 -

在A.php中 -

class A {
    public function testA(){
        echo "AA";
    }
}

在B.php中 -

class B extends A{
    public function testB(){
        echo "BB";
    }
}

在C.php中 -

class C extends B{
    //Here i am able to call class B's function like 
    public function testC(){
        $this->testB();
    }

    //but not able to call Class A's function 
    public function testC1(){
        $this->testA();  // Here its giving error
    }
}

请让我知道这是正确的方法。如何在'C.php'中访问'A.php'功能

问候

php class inheritance multiple-inheritance
1个回答
0
投票

如果你发布错误信息,那很可能是内存不足,对吧?那是因为你的代码中有一个无限循环。

在班级C,你有

public function testB() 
{ 
    $this->testB(); 
} 

这是一种永远称之为自我的方法,耗尽了你拥有的所有记忆。

如果你想从父类调用testB(),你应该调用它:

public function testB() 
{ 
    parent::testB(); 
} 

如果你扩展了一个类并重写了一个方法(比如你的testB()类中的C)并且想要调用parent实现,你需要使用parent::而不是$this->来调用它。

Here's a demo

© www.soinside.com 2019 - 2024. All rights reserved.