首页 > 解决方案 > 在php中调用顶级类函数

问题描述

我有一个场景,我有三个单独的类文件 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”函数

问候

标签: phpclassinheritancemultiple-inheritance

解决方案


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

在课堂C上,你有

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

这是一种永远调用它的方法,用完你所有的内存。

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

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

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

这是一个演示


推荐阅读