Home >PHP Framework >ThinkPHP >How to set the constructor in ThinkPHP
1. What is a constructor function
The constructor is a special function that is automatically called when instantiating an object. Its function is to initialize the object, set the initial value of the properties, etc. In PHP, the name of the constructor must be __construct().
2. Steps to set the constructor in ThinkPHP
First we need to create a class file, for example we can create a PHP file , named test.php, the code is as follows:
<?php namespace Home\Model; use Think\Model; class test extends Model{ private $name; public function __construct($name){ $this->name = $name; } public function get_name(){ return $this->name; } }
In the test class, a private attribute $name is defined, and there is also a public method get_name( ). We use the $name parameter to assign an initial value to the $name attribute in the constructor __construct().
When using the test class, we can instantiate the object as follows:
$t = new test("thinkphp"); echo $t->get_name();
Instancing At the same time as the object, we passed a string "thinkphp" as a parameter. This parameter will be passed to the constructor __construct() of the class and used to set the initial value of the attribute $name. Finally, we use the get_name() function to extract the value of the $name attribute and output it.
3. Advantages of using constructors
The advantage of using constructors is that you can complete some necessary tasks when the class is instantiated. Initialization operation avoids writing some additional initialization code when using classes. In this way, it is more convenient to use.
The above is the detailed content of How to set the constructor in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!