Home Backend Development PHP Tutorial Inheritance analysis of constructors in php

Inheritance analysis of constructors in php

Jul 02, 2017 am 10:02 AM
php analyze inherit

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!

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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles