soxthinkphp __construct和_initialize
thinkphp框架中,__construct和_initialize是两个常用的方法,它们分别在对象实例化和初始化时被调用。虽然它们的功能有一些重叠,但是使用方法和调用时机略有不同。
__construct方法是php类中的一种特殊方法,当一个对象被创建时自动调用。在thinkphp框架中,我们可以利用__construct方法来初始化一些成员变量,例如数据库连接信息、用户信息等。例如:
```php
<?php
namespace appindexcontroller;
u thinkController;
class Index extends Controller
{玻璃杯的英文
美国大选2020时间表 protected $db;
protected $ur;
入口门
public function __construct()
{
$this->db = new PDO('mysql:host=localhost;dbname=test', 'root', 'password');
$this->ur = ssion('ur');
}
stamped public function index()
nong
{
//
}
}
```
_initialize方法也是thinkphp框架中常用的初始化方法,它的调用时机是在控制器对象实例化后,并且在beforeAction方法之前调用。在_initialize方法中,我们可以完成一些控制器的初始化工作,例如设置模板变量、判断用户是否登录等。例如:
```php
<?php
namespace appindexcontroller;
u thinkController;
class Index extends Controller
杭州英语翻译 {
protected $db;
protected $ur;
热播美剧排行榜2013 protected function _initialize()
{2015上海高考
$this->ur = ssion('ur');
if (!$this->ur) {
$this->error('请先登录');
}
$this->assign('ur', $this->ur);
}
public function index()
{
//
}
}
```
需要注意的是,__construct方法在控制器对象实例化时被调用,而_initialize方法则是在beforeAction方法之前调用。控制器中的__construct和_initialize方法都是可选的,根据需要进行使用。
>ininline