The previous article introduced you to "What are classes and objects in PHP? Why learn object-oriented? how to use? 》, this article continues to introduce to you how to use the constructor and this keyword in PHP? How to introduce constructor? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Construction method and this keyword:
Introducing the construction method
Create When creating an object, we need to initialize the object. At this time, we need to call our constructor. The constructor is automatically called, not manually. It is a magic method
__construct ()
Constructor without passing parameters
Create object and call directly|
Constructor with parameters passed
$this:当前对象, $this->name ; $this->cook() ;
<?php class Person { public $poet ='林徽因'; public $pome= '答案很长,我准备用一生的时间来回答,你准备要听了吗?'; } $ming = new Person(); var_dump( $ming); echo '<br>'; $niu = new Person(); var_dump ($niu); ?>
<?php class Person { public $poet; public $pome; } $ming = new Person(); $ming->poet = '林徽因' ; $ming->pome = '答案很长,我准备用一生的时间来回答,你准备要听了吗?'; var_dump ( $ming); echo '<br>'; $niu = new Person(); $niu->name = '张爱玲'; $niu->age = '你还不来,我怎敢老去'; var_dump($niu);
The above is the detailed content of How to use constructor and this keyword in PHP? How to introduce constructor?. For more information, please follow other related articles on the PHP Chinese website!