PHP超类和子类 [英] PHP superclass and subclass

查看:92
本文介绍了PHP超类和子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,以下内容有意义吗?

A simple question, does the following make sense ?

B级扩展了A级

A类构造函数:

function __construct(){
    //do something
}

B类构造函数:

function __construct(){
    parent::__construct();
}

在这种情况下,实现子构造函数是否有明显的优势?

Is there any significant advantage to implementing the child constructor at all in this case?

我只能想到:

  • B类的整个代码在结构上将更加完整"

很高兴知道在编码或结构化方面是否有任何明显的优势.

Would be interesting to know if there is any significant advantages in coding or in structuring etc.

推荐答案

您唯一要从子类(子类)中调用父构造函数的时间是想在构造函数中添加自定义代码.

The only time you want to invoke your parent constructor from your subclass (child class) is when you want to add custom code in your constructor.

在您的示例中,您可以在类B中完全省略__construct()方法.

In your example you can leave out the __construct() method altogether in Class B.

但是您可能想要执行以下操作:

However you might want to do something like this:

class A {

  function __construct() {
    run_a_function();
    $this->set = "a variable";
  }

}

class B {

  function __construct() {
    run_a_function_specific_to_class_b();
    $this->set = "a variable specific to class b";

    // now call the parent constructor
    parent::__construct();
  }

}

这篇关于PHP超类和子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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