PHP-扩展__construct [英] PHP - extended __construct

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

问题描述

我想知道您是否可以帮助我。.

I was wondering if you could help me out..

我有两个类,一个扩展了另一个。.B类将由各种不同的对象扩展,并且用于普通的数据库交互。现在,我希望B类处理其连接和断开连接,而无需从A类或任何外部输入进行指示。.

I have two classes, one extends the other.. Class B will be extended by various different objects and used for common database interactions.. Now I would like class B to handle its connect and disconnects without direction from class A or any external input..

我所遇到的问题理解是扩展类不会自动运行其__construct函数。.有没有解决的办法?

The problem from what I understand is that an extended class won't automatically run its __construct function.. Is there a way around this?

预先表示感谢。.

class a extends b
{
   public function __construct()
   {
   }   

   public function validateStuff()
   {
      $this->insert_record();
   }
}

class b
{
   public function __construct()
   {
      $this->connect();
   }

   protected function connect()
   {
      return true;
   }

   public function insert_record()
   {
      return true;
   }
}


推荐答案

如果实例化子类A,则在类b中定义的父 __ construct()方法将自动运行,除非,其中有一个 __ construct ()方法在类a中定义。

The parent __construct() method defined in class b will run automatically if you instantiate child class a, unless there is a __construct() method defined in class a.

class a extends b { 
} 

class b { 
   public function __construct() 
   { 
      echo 'In B Constructor'; 
   } 
} 

$x = new a();

如果定义了 __ construct()方法在类A中,那么它将覆盖在类b中使用 __ construct()方法...。它将代替类b运行 __ construct()方法

If a __construct() method is defined in class a, then this overrides the use of the __construct() method in class b.... it will run instead of the class b __construct() method

class a extends b { 
   public function __construct() 
   { 
      echo 'In A Constructor'; 
   } 
} 

class b { 
   public function __construct() 
   { 
      echo 'In B Constructor'; 
   } 
} 

$x = new a();

因此,如果您的孩子班级有 __ construct()定义了方法,然后也要显式调用父级的构造函数。

So if your child class has a __construct() method defined, then you need to explicitly call the constructor for the parent if you want to execute that as well.

class a extends b { 
   public function __construct() 
   { 
      parent::__construct();
      echo 'In A Constructor'; 
   } 
} 

class b { 
   public function __construct() 
   { 
      echo 'In B Constructor'; 
   } 
} 

$x = new a();

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

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