


PHP object-oriented-code case sharing of constructor and destructor methods
Construction method and Destruction method are two special methods in object, they are both related to the life cycle of the object . The constructor method is The first method that is automatically called by the object after the object is created. This is the reason why we use the constructor method in the object. The destructor method is the last method that is automatically called by the object before it is destroyed. This is why we use the destructor method in the object. Therefore, the construction method is usually used to complete the initialization work of some objects, and the destructor method is used to complete the cleaning work of some objects before destruction. 1. Constructor method
# In each declared class, there is a special member method called a constructor method. If there is no If you declare it explicitly, there will be a constructor with no parameter list and empty content in the class by default. If you declare it explicitly, the default constructor in the class will not exist. When an object is created, the constructor method will be automatically called once, that is, the constructor method will be automatically called every time the keyword new is used to instantiate the object. The constructor method cannot be actively called through a reference to the object. Therefore, constructors are usually used to perform some useful initialization tasks, such as assigning initial values to member properties when creating objects. In previous versions of PHP5, the method name of the constructor must be the same as the class name. This method can still be used in PHP 5. But in PHP, it is rare to declare a constructor with the same name as the class name. The advantage of this is that the constructor can be independent of the class name. When the class name changes, there is no need to change the corresponding constructor name. For backward compatibility, when creating an object, if there is no constructor named construct() in a class, PHP will search
for a constructor with the same name as the class name and execute it. The format for declaring a constructor in a class is as follows:function construct( [参数列表] ){ //构造方法名称是以两个下划线开始的 //方法体,通常用来对成员属性进行初始化赋值}
In PHP, only one constructor can be declared in the same class. The reason is that the constructor method name is fixed, and two functions with the same name cannot be declared in PHP, so there is no constructor method overloading. However, you can use default parameters when declaring the constructor to realize the function of constructor overloading in other object-oriented
programming languages. In this way, when creating an object, if no parameters are passed in the constructor, default parameters are used to initialize member properties. The constructor can accept parameters and can assign values to object properties when creating an object
The constructor can call class methods or other functions
The constructor can call the constructor of other classes
Constructor usage example: <?phpclass Person{ private $name; private $age; private $gender; public function construct($name,$age,$gender){ $this->setName($name); //调用类方法 $this->age = $age; $this->setGender($gender); } public function setName($name){ $this->name = $name; } // ... setter 方法}$person = new Person("yeoman",23,'男');?>
Copy after login
Call the parent class constructor, call Constructors of unrelated classes:function construct(){ parent::construct(); // 调用父类的构造函数必须显示的使用parent调用父类构造函数 classname::construct(); // 调用其他类的构造函数,classname是类名 //其他操作}
Copy after login
Inheritance
and constructors The constructor of a subclass in PHP will not actively call the constructor of the parent class. To be displayed, use parent::construct() call: <?php
class Animal{
private $name;
function construct($name){
$this->setName($name)
echo "动物类被创建!";
} // ... 其他方法}class Birds extends Animal{
private $name;
private $leg;
function construct($name,$leg){
parent::construct($name); // 显示调用
$this->setLeg($leg);
echo "鸟类被创建!";
} // ... 其他方法}?>
// 接上例class Parrot extends Birds{ private $name; private $leg; private $wing; function construct($name){ parent::construct($name); // 此时没有找到父类(Birds类)合适的构造函数,只能向上搜索,搜索到Animal类时,才找到合适的构造函数 echo "鹦鹉类被创建!"; $this->smackTalk(); /* 输出结果: "动物类被创建!" "鹦鹉说话!" */ } function smackTalk(){ echo "鹦鹉说话!"; } }
If you want to call the constructors of several parent classes in sequence, you can use the class name to call the constructor directly, for example:
function construct($name,$leg){ Animal::construct($name); // 调用Animal构造函数 Birds::construct($name,$leg); // 调用Birds构造函数}
2.
DestructorThe destructor method allows you to perform some specific operations before destroying an object, such as closing the file, releasing the result set, etc. When an object in the heap memory segment loses the reference to access it, it cannot be accessed and becomes a garbage object. Usually the reference to the object is assigned another value or the object loses its reference when the page ends. The destructor is automatically called when the object is destroyed and cannot be called explicitly. The destructor cannot take parameters.
The declaration format of the destructor method is as follows:
function deconstruct(){ //方法体,通常用来完成一些在对象销毁前的清理任务}
The destructor may be called (but not necessarily) in the following situations:
After the PHP page is loaded;
unset() class;
- Variable refers to another object or value When;
PHP's memory recycling mechanism is very similar to JAVA's. Objects without any references are destroyed and recycled using reference counter technology.
example:
<?php class test{ function destruct(){ echo "当对象销毁时会调用!!!"; } }$a = $b = $c = new test();$a = null;unset($b);echo "<hr />";?>
Copy after login此例子,如下图,有三个变量引用$a,$b,$c指向test对象,test对象就有3个引用计数,当$a = null时,$a对test对象的引用丢失,计数-1,变为2,当$b被unset()时,$b对test对象的引用也丢失了,计数再-1,变为1,最后页面加载完毕,$c指向test对象的引用自动被释放,此时计数再-1,变为0,test对象已没有变量引用,就会被销毁,此时就会调用析构函数。
在PHP中析构方法并不是很常用,它属于类中可选的一部分,只有需要时才在类中声明。
<?phpclass Person{ var $name; var $sex; var $age; function construct($name, $sex, $age){ $this->name = $name; $this->sex = $sex; $this->age = $age; } function destruct(){ echo "再见" . $this->name . "<br />"; } } $person1 = new Person("张三三", "男", 23); $person1 = null; //第一个对象将失去引用 $person2 = new Person("李四四", "女", 17); $person3 = new Person("王五五", "男", 43); ?>
Copy after login运行结果:
再见张三三 再见王五五 再见李四四
Copy after login第一个对象在声明完成以后,它的引用就被赋予了空值,所以第一个对象最先失去的引用,不能再被访问了,人后自动调用第一个对象中的析构方法输出“再见张三三”。后面声明的两个对象都是在页面执行结束时失去的引用,也都自动调用了析构方法。但因为对象的引用都是放在栈内存中的,由于栈的后进先出特点,最后创建的对象会被最先释放,多以先自动调用第三个对象的析构方法,最后才调用第二个对象的析构方法。
The above is the detailed content of PHP object-oriented-code case sharing of constructor and destructor methods. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
