一、什么是构造函数
构造函数是一个在实例化一个对象时自动调用的特殊函数。它的作用是对对象进行初始化,设置属性的初始值等。在PHP中,构造函数的名称必须为__construct()。
二、在ThinkPHP中设置构造函数的步骤
首先我们需要创建一个类文件,比如说我们可以创建一个PHP文件,命名为test.php,代码如下:
<?php
namespace HomeModel;
use ThinkModel;
class test extends Model{
private $name;
public function __construct($name){
$this->name = $name;
}
public function get_name(){
return $this->name;
}
}
在test类里面,一个私有属性 $name 被定义,同时还有一个公共方法 get_name()。我们使用$name参数在构造函数__construct()中为$name属性赋初值。
在使用test类的时候,我们可以像下面这样实例化对象:
$t = new test("thinkphp");
echo $t->get_name();
在实例化对象的同时,我们传递了一个字符串"thinkphp"作为参数,这个参数将被传递给类的构造函数__construct(),并被用来设置属性$name的初值。最终,我们用get_name()
.........................................................