Inheritance analysis of constructors in php

黄舟
Release: 2023-03-12 10:28:02
Original
1664 people have browsed it

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();
?>
Copy after login

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
    }
}
?>
Copy after login

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();
Copy after login

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("苹果");
 
// 输出 水果苹果创建了
?>
Copy after login

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
Copy after login

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!";
}
Copy after login

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!";
}
Copy after login

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;
Copy after login

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;;
  }
}
Copy after login

注意 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;
Copy after login

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;
   }
}
?>
Copy after login

下面来检查一下用拷贝运算符 = 创建的 $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 */
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!