为啥加载模型和加载类库的时候非要在构造函数里
为啥我直接在方法里面加载model或library必须在CLASS的构造器里,如果直接在function 里加载就报没有定义的错呢?必须在构造器里加载真让我想不通,是有地方设置的吗。例如
function HelloWord(){
parent::Controller();
$this->load->model('Infomodel');
$config['upload_path'] = 'D:/wamp/www/info//uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100067';
$config['max_width']= '102475';
$config['max_height']= '76888';
$this->load->library('upload', $config);
} 。。。。。。
这样就没问题,如果是
。。。。。。。。。
function insertinfo(){
$this->load->model('Infomodel'); //如果不在构造函数里加载,而在使用的时候才加载,就报错,谁能帮忙解答这个问题
$result = $this->Infomodel->selectinfo();
$data = array('infos'=>$result);
$this->load->view("insertinfo",$data);
} 是你程序的问题~~~
model一般都是在方法里加载,而不是构造函数 很简单的一个程序啊, $this->load->model('Infomodel');我刚才试了,这个如果直接放在构造函数里面,程序就没问题,如果放在function 里面就报错
A PHP Error was encountered
Severity: Notice
Message: Undefined property: HelloWord::$Infomodel
Filename: controllers/helloword.php
Line Number: 24
我也觉得不合理,开始都没注意,后来在写一个上传文件的例子的时候,发现加载liberary也是要在构造函数里,要不然也报错,我就有点晕了,那位达人解答一下,多谢
[ 本帖最后由 gz123 于 2008-5-22 16:26 编辑 ] 随便写了个测试程序
控制器 test.php
<?php
class Test extends Controller {
function Test(){
parent::Controller();
}
function test1() {
$this->load->model('Testmodel'); //模型在方法里加载
$str = $this->Testmodel->getstr();
echo $str;
}
}
?>
模型 testmodel.php
<?php
class Testmodel extends Model {
function Testmodel()
{
parent::Model();
}
function getstr(){
return "dddddddd";
}
}
?>
运行后报错
A PHP Error was encounteredSeverity: Notice
Message: Undefined property: Test::$Testmodel
Filename: controllers/test.php
Line Number: 11
Fatal error: Call to a member function getstr() on a non-object in D:\wamp\www\info\system\application\controllers\test.php on line 11
如果把test.php 改成
控制器 test.php
<?php
class Test extends Controller {
function Test(){
parent::Controller();
$this->load->model('Testmodel'); //模型在构造器里加载
}
function test1() {
$str = $this->Testmodel->getstr();
echo $str;
}
}
?>
显示结果 dddddddd
肯定不是程序的错,是环境的问题????用的是CodeIgniter1.6.2 ,在windows下调试的,PHP版本是5.2.3 很郁闷,那位好心人能解惑 从你的代码看没发现什么问题。
你报错的是哪行?load这行? 报错不是load的这行,是$str = $this->Testmodel->getstr(); 这一行,就是调用模型里面的方法的这行,说这个Testmodel属性没有定义,但是如果在构造函数里load,这行就不报错
[ 本帖最后由 gz123 于 2008-5-22 16:10 编辑 ] 好像和我的本地环境有问题,我换一个LINUX下就正常了,郁闷 呵呵,看来就是环境问题。 Unable to locate the model you have specified: article_model
为什么我报这样的错误呢? 怎么找不到模型函数啊?
页:
[1]
2