【问题标题】:Can we call parent method out side of the class我们可以在类之外调用父方法吗
【发布时间】:2015-04-08 11:39:24
【问题描述】:

我有如下父子类:

// class A
class A {
    public function test(){
        echo "CLASS A";
    }

}

// class b which is extending class A
class B extends A{
    public function test(){        
        echo "CLASS B";
    }

}

$class = new B;
$class->test();  //It's calling child class function.

有什么方法可以用$class 调用父类方法吗?我知道我也可以为 A 类创建一个对象并调用该函数,但我想从子类对象调用父类方法。

这在php中可行吗?

【问题讨论】:

  • @hek2mgl 我也猜 :)
  • 为什么对此投反对票,我想知道......即使我在谷歌上搜索后发布并没有找到任何相关答案。

标签: php class oop inheritance


【解决方案1】:

试试看:

class B extends A{
    public function test(){        
        echo parent::test();
    }

}

更多详情:http://php.net/manual/en/keyword.parent.php

【讨论】:

  • @manish 基本上就是这样做的。如果您想在类之外公开这两个函数,则您的代码中存在设计错误,或者如果它们不同,则需要为这些函数指定不同的名称。
  • 对不起,如果我打扰了,我是 OOP 的新手,但是在子类中他不是覆盖父类的test() 方法吗?
  • 是的,他是,但他仍然可以从类内部调用基类方法。
  • 在父类里面没问题。我知道这一点。但我对此很好奇。我认为不可能从基类对象调用父类同名方法。
猜你喜欢
  • 1970-01-01
  • 2012-01-09
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-14
  • 2017-12-27
相关资源
最近更新 更多