Home > Backend Development > PHP Tutorial > php constructor and destructor_php skills

php constructor and destructor_php skills

WBOY
Release: 2016-05-16 19:53:53
Original
1260 people have browsed it

The PHP constructor is the first method automatically called after the object is created, and the destructor is the last method automatically called before the object is released. This article introduces you to the PHP constructor and destructor.

php constructor

1. It is the "first" "automatically called" method after the object is created
2. The definition of the constructor method, the method name is fixed,

In php4: The method that is the same as the class name is the construction method
In php5: The constructor method is selected using the magic method __construct(). This name is used to declare constructors in all classes

Advantage: When changing the class name, the constructor method does not need to be changed

Magic method: If a magic method is written in the class, the function corresponding to this method will be added
The method names are all fixed (all provided by the system), there are no self-defined ones
Every magic method is a method that is automatically called at different times to complete a certain function
Different magic methods have different calling times
All methods start with __
__construct(); __destruct(); __set();......

Function: Initialize member attributes;

php destructor

1. The last "automatically" called method before the object is released
Use garbage collector (java php), and c manual release
Function: Close some resources and do some cleanup work

__destruct();

php constructor and destructor examples

class Person{ 
var $name; 
var $age; 
var $sex; 
//php4中的构造方法 
/*function Person() 
{ 
//每声明一个对象都会调用 
echo "1111111111111111"; 
}*/ 
//php5中的构造方法 
function __construct($name,$age,$sex){ 
$this->name=$name; 
$this->age=$age; 
$this->sex=$sex; 
} 
function say(){ 
//$this->name;//对象中成员的访问使用$this 
echo "我的名字:{$this->name},我的年龄:{$this->age}<br>" 
} 
function run(){ 
} 
function eat(){ 
} 
//析构方法 
function __destruct(){ 
} 
} 
$p1=new Person("zhangsan",25,"男"); 
$p2=new Person; 
$p3=new Person; 
Copy after login

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