The construction method is a special method of the class, the main function is to complete the initialization of the new object.
Features of the construction method:
(1) no return value;
(2) When creating a new object for a class, the system automatically calls the constructor of the class to complete initialization of the new object.
(3) in PHP5, a class can have two forms of construction methods, __construct and class names (), and when two appear simultaneously, the first one is selected. Try to use the first form of the constructor.
Considerations of construction methods;
1. Once a constructor is customized, the default constructor is overwritten, and the custom constructor is used when creating the object.
2. A class can have only one constructor and cannot be overloaded.
3. The default access modifier for the construction method is public
Example: When creating a human class, initialize $name and $age
Cases:
<?php
Class person{
Public $name;
Public $age;
The construction method of PHP5
Public Function __construct () {
echo "I am the construction method!";
}
/*//PHP4, the name and class name are the same
Public Function person () {
echo "PhP4 Method of construction!";
}
*/
}
$p 1=new person ();
?>
How to understand $this?
1, $this in nature can be understood to be the address of this object;
2, which object uses to $this, is which object's address;
3, $this can not be used outside the class.
Example 2:
<?php
Class person{
Public $name;
Public $age;
Public Function __construct () {
The system assigns each object a this, representing the current object
$this->name= "www.bianceng.cn";
$this->age=10;
}
}
$p 1=new person ();
echo "$p 1->name is". $p 1->age. "Years old!";
?>