The function of the constructor in php is to initialize the object when creating it, that is, to assign initial values to the object member variables. Constructors are always used with the new operator in statements that create objects. A class can have multiple constructors.
Constructor function
The constructor is a special method, mainly used to initialize the object when creating the object, that is, the object member variable Assign initial value. It is always used with the new operator in statements that create objects. A class can have multiple constructors, which can be distinguished based on the number of parameters or the types of parameters, that is, the overloading of constructors.
Example:
We first create a class and initialize this class.
class Preson{ public $name; //定义变量 public $age; public $sex; public $height; function __construct($name,$age,$sex,$height){ $this->name = $name; //为变量赋值 $this->age = $age; $this->sex = $sex; $this->height = $height; } public function PlayBaskteBall(){ if($this->height>175 || $this->age < 22){ return $this->name . "可以打篮球"; }else{ return $this->name . "不具备打球的条件"; } } } $Preson1 = new Preson("大白","20","女","180"); echo $$Preson1->PlayBaskteBall();
The constructor is used when initializing the object. If there is no constructor, PHP will automatically generate one. The automatically generated constructor has no parameters and no operations.
If you want to learn more related knowledge, please visit php Chinese website.
The above is the detailed content of What is the role of constructor in php. For more information, please follow other related articles on the PHP Chinese website!