如何在PHP的子级构造函数中访问父级方法? [英] How do I access a parent's methods inside a child's constructor in PHP?

查看:95
本文介绍了如何在PHP的子级构造函数中访问父级方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有个class child() class parent()。父级有一个构造函数和其他一些公共方法,而子级除了构造函数外都是空的。

Say I have class child() and class parent(). The parent has a constructor and a few other public methods, and the child is empty apart from a constructor.

我该如何在子级内部调用父级的方法构造函数,例如:

How do I go about calling a parent's methods inside of the child's constructor, as in:

Class Parent {
    public function __construct() {
       // Do stuff (set up a db connection, for example)
    }

    public function run($someArgument) {
       // Manipulation
       return $modifiedArgument;
    }
} 

Class Child extends Parent {
    public function __construct() {
      // Access parent methods here?
    }  
}

说我想打 parent s run()方法,我是否必须在子构造函数中调用父级的新实例?像这样...

Say I want to call parents run() method, do I have to call a new instance of the parent inside the child constructor? Like so...

$var = new Parent(); 
$var->run($someArgument);

如果是这样,扩展的意义是什么从类定义POV?无论是否扩展子级,我都可以使用 new 关键字调用另一个类的新实例。

If so, what is the point of extends from a class definition POV? I can call a new instance of another class with the new keyword whether it extends the 'child' or not.

我(可能)错误的理解是,通过使用 extends ,您可以链接类,而父类的方法可以继承到子类中。那只是 outside 类的定义吗?使用 extend 不会在类定义内提供任何效率吗?

My (likely) wrong understanding was that by using extends you can link classes and methods from a parent can be inherited into the child. Is that only outside the class definition? Does using extend offer no efficiencies inside the class definition?

因为用 this run()方法$ c>关键字肯定不起作用...

Because referring to the parent's run() method with the this keyword certainly doesn't work...

推荐答案

使用父级作为预定义引用: parent :: run()。这将确保您调用父方法。用相同的方法可以先调用第一个父级构造函数,也可以在子级后一个子调用- parent :: __ construct()

Use parent as predefined reference: parent::run(). This will ensure you call parent method. The same way you could call first parent constructor first or after child one - parent::__construct().

Class Child extends Parent {
    public function __construct() {
      parent::__construct();
      // Access parent methods here?
      $some_arg = NULL; // init from constructor argument or somewhere else
      parent::run($some_arg); // explicitly call parent method
      // $this->run($some_arg); // implicitly will call parent if no child override
    }  

}

如果您的孩子没有实现,则可以调用 $ this-> run($ args),它将再次调用父运行方法。

If you dont have an implementation in child you could call $this->run($args), where it will again call parent run method.

这篇关于如何在PHP的子级构造函数中访问父级方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆