search
HomeBackend DevelopmentPHP TutorialInheritance analysis of constructors in php
Inheritance analysis of constructors in phpJul 02, 2017 am 10:02 AM
phpanalyzeinherit

ConstructorUsage

HP 5 allows developers to define a method as a constructor in a class. Classes with a constructor will call this method every time a new object is created, so it is very suitable for doing some initialization work before using the object.

Note: If a constructor is defined in a subclass, the constructor of its parent class will not be called implicitly. To execute the parent class's constructor, you need to call parent::construct() in the child class's constructor. If the subclass does not define a constructor, it will be inherited from the parent class like an ordinary class method (if it is not defined as private).
Example #1 Using the new standard constructor

<?php
class BaseClass {
   function construct() {
       print "In BaseClass constructorn";
   }
}
class SubClass extends BaseClass {
   function construct() {
       parent::construct();
       print "In SubClass constructorn";
   }
}
class OtherSubClass extends BaseClass {
    // inherits BaseClass&#39;s constructor
}
// In BaseClass constructor
$obj = new BaseClass();
// In BaseClass constructor
// In SubClass constructor
$obj = new SubClass();
// In BaseClass constructor
$obj = new OtherSubClass();
?>

For backward compatibility, if PHP 5 cannot find the construct() function in the class and does not inherit one from the parent class, it It will try to find the old-style constructor, which is a function with the same name as the class. So the only time a compatibility issue arises is when the class already has a method named construct() but it is used for other purposes.

Unlike other methods, PHP will not generate an E_STRICT error message when construct() is overridden by a method with different parameters than the parent class construct().

Since PHP 5.3.3, in the namespace, the method with the same name as the class name is no longer a constructor. This change does not affect classes that are not in the namespace.

Example #2 Constructors in namespaced classes

<?php
namespace Foo;
class Bar {
    public function Bar() {
        // treated as constructor in PHP 5.3.0-5.3.2
        // treated as regular method as of PHP 5.3.3
    }
}
?>

Assign an initial value when creating an object.

1. //创建一个人类  
2.  
3. 0class Person   
4. 0{   
5. //下面是人的成员属性   
6. var $name;       //人的名子   
7. var $sex;        //人的性别   
8. var $age;        //人的年龄   
9. //定义一个构造方法参数为姓名$name、性别$sex和年龄$age   
10. function construct($name, $sex, $age)   
11. {   
12. //通过构造方法传进来的$name给成员属性$this->name赋初使值   
13. $this->name=$name;   
14. //通过构造方法传进来的$sex给成员属性$this->sex赋初使值   
15. $this->sex=$sex;   
16. //通过构造方法传进来的$age给成员属性$this->age赋初使值   
17. $this->age=$age;   
18. }   
19. //这个人的说话方法   
20. function say()   
21. {  
22. echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."<br>";   
23. }   
24. }   
25. //通过构造方法创建3个对象$p1、p2、$p3,分别传入三个不同的实参为姓名、性别和年龄  
26. $p1=new Person("张三","男", 20);   
27. $p2=new Person("李四","女", 30);   
28. $p3=new Person("王五","男", 40);   
29. //下面访问$p1对象中的说话方法   
30. $p1->say();   
31. //下面访问$p2对象中的说话方法   
32. $p2->say();   
33. //下面访问$p3对象中的说话方法   
34. $p3->say();

The output result is:

My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My Age is: 30
My name is: Wang Wu Gender: Male My age is: 40

Inheritance problem of constructor

Let’s look at a simple example first:

<?php
class Fruit {
public function construct($name)
{
echo &#39;水果&#39;.$name.&#39;创建了&#39;;
}
}
 
class Apple extends Fruit {
public function construct($name)
{
parent::construct($name);
}
}
 
$apple = new Apple("苹果");
 
// 输出 水果苹果创建了
?>

The inheritance of the constructor saves the rewriting of the code rather than the declaration of the method. That is to say, the constructor declared in the parent class must be declared again in the subclass. In fact, this is also a The process of rewriting.

PHP's constructor inheritance must meet the following conditions:

When the parent class has a constructor declaration, the subclass must also have a declaration, otherwise an error will occur.
When executing the constructor of the parent class, the parent keyword must be quoted in the subclass.
If the parent class has a constructor and the subclass does not have a constructor, the parent class constructor will indeed be executed when the subclass is instantiated. For example, suppose the Employee class has the following constructor:

function  construct($name){
$this->setName($name);
}
然后实例化CEO类,获得其name成员:

$ceo= new CEO("Gonn");
echo $ceo->getName();
将得到如下结果:

My name is Gonn

However, if the subclass also has a constructor, then when the subclass is instantiated, it will be executed regardless of whether the parent class has a constructor. The subclass's own constructor. For example, assume that in addition to the Employee class containing the above constructor, the CEO class also contains the following constructor:

function  construct(){
echo "CEO object created!";
}

Instantiate the CEO class again and execute getName() in the same way. This time you will get different output:


CEO object created!

My name is Gonn
When encountering parent::construct(), PHP starts searching upwards along the parent class for a suitable constructor. Because it was not found in Executive, we continued to search for the Employee class and found the appropriate constructor here. If PHP finds a constructor in the Employee class, it will execute the constructor. If you want to execute both the Employee constructor and the Executive constructor, you need to call parent::construct() in the Executive constructor.

In addition, you can choose another way to reference the constructor of the parent class. For example, assume that when a new CEO object is created, both the Employee and Executive constructors are executed. As mentioned above, these constructors can be referenced explicitly in the CEO's constructor, as follows:

function construct($name){
Employee::constrcut($name);
Executive::construct();
echo "CEO object created!";
}

Constructor inheritance in different PHP versions

References in constructors


The constructor name of PHP 4.x is the same as the class name.
The constructor name of the subclass is the same as the subclass name (nonsense).
The constructor of the parent class will not be executed automatically in the subclass.
To execute the constructor of the parent class in the subclass, you must execute a statement similar to the following:
$this->[Constructor name of the parent class ()]

For example:

class base1
{
  function base1()
  {
echo &#39;this is base1 construct&#39;;
  }
}
class class1 extends base1
{
  function class1()
  {
$this->base1();
echo &#39;this is class1 construct&#39;;
  }
}
$c1 = new class1;

PHP5.x Version:

PHP5.0 or above has greatly expanded the functions of the class. The constructor of a class is uniformly named construct().
The constructor name of the subclass is also construct() (also nonsense).
Whether the constructor of the parent class will be executed in the subclass can be divided into two situations:
1. If the subclass does not define the constructor construct(), the constructor of the parent class will be inherited by default. And it will be executed automatically.
2. If the subclass defines the constructor construct(), because the name of the constructor is also construct(), the constructor of the subclass actually overrides the constructor of the parent class. What is executed at this time is the constructor of the subclass.
At this time, if you want to execute the constructor of the parent class in the subclass, you must execute a statement similar to the following:

parent::construct();

For example:

class base2
{
  function construct()
  {
echo &#39;this is base2 construct&#39;;
  }
  function destruct()
  {
  }
}
class class2 extends base2
{
  function construct()
  {
parent::construct();
echo &#39;this is class2 construct&#39;;
  }
}

注意 parent::construct(); 语句不一定必须放在子类的构造函数中。放在子类的构造函数中仅仅保证了其在子类被实例化时自动执行。

PHP4.0 和 5.0 类构造函数的兼容问题:

在 PHP5.0 以上版本里,还兼容了 4.0 版本的构造函数的定义规则。如果同时定义了4.0的构造函数和 construct()函数,则construct() 函数优先。
为了使类代码同时兼容 PHP4.0 和 5.0,可以采取以下的方式:

class class3
{
  function construct() //for PHP5.0
  {
echo &#39;this is class2 construct&#39;;
  }
  function class3() //for PHP4.0
  {
$this->construct();
  }
}
$c3 = new class3;

php构造函数中的引用的内容。

<?php
class Foo {
   function Foo($name) {
     
       global $globalref;
       $globalref[] = &$this;
  
       $this->setName($name);
      
       $this->echoName();
   }
   function echoName() {
       echo "<br />",$this->name;
   }
   function setName($name) {
       $this->name = $name;
   }
}
?>

下面来检查一下用拷贝运算符 = 创建的 $bar1 和用引用运算符 =& 创建的 $bar2 有没有区别...
copy to clipboard
显然没有区别,但实际上有一个非常重要的区别:$bar1 和 $globalref[0] 并没有被引用,它们不是同一个变量。这是因为“new”默认并不返回引用,而返回一个拷贝。

<?php
$bar1 = new Foo(&#39;set in constructor&#39;);
$bar1->echoName();
$globalref[0]->echoName();
/* &#36755;&#20986;&#65306;
set in constructor
set in constructor
set in constructor */
$bar2 =& new Foo(&#39;set in constructor&#39;);
$bar2->echoName();
$globalref[1]->echoName();
/* &#36755;&#20986;&#65306;
set in constructor
set in constructor
set in constructor */
?>

The above is the detailed content of Inheritance analysis of constructors in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools