Home  >  Article  >  Backend Development  >  php constructor

php constructor

巴扎黑
巴扎黑Original
2016-11-22 10:45:431246browse

Starting from php5, you can declare the __construct constructor method in the class. When the object is instantiated, this method is called.
Note:
1. If there is no constructor method in the inherited subclass but there is a constructor method in the parent class, then when the subclass is instantiated, the constructor method of the parent class will be called implicitly.
2. If the subclass has a constructor and the parent class also has a constructor, then the subclass must explicitly call parent::__construct() to access the parent class's constructor.
3. For forward compatibility, if the __construct() method is not found in the php5 class, it will look for a constructor with the same method name as the class name.

class Person{
public $sex = '男';
function __construct() {
echo 'parent __construct';
}
}
class Student extends Person{
private $id;
private $name;
private $age;
//构造函数
function __construct($id,$name,$age) {
parent::__construct();
echo '__construct';
$this->id = $id;
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
//析构函数
function __destruct(){
echo '__destruct';
}
}
$su = new Student('id001','张三',20);
echo $su->getName();
echo $su->sex;

Print result:

parent __construct
__construct
Zhang San
Male
__destruct


Statement:
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