我正在测试这个东西,我试图加载一个类并像这样使用它:
$this->model->model_name->model_method();
这就是我所拥有的:
<?php
error_reporting(E_ALL);
class Loader {
public function model($model)
{
require_once("models/" . $model . ".php");
return $this->model->$model = new $model;
}
}
class A {
public $load;
public $model;
public $text;
public function __construct()
{
$this->load = new Loader();
$this->load->model('Test');
$this->text = $this->model->Test->test_model();
}
public function get_text()
{
return $this->text;
}
}
$text = new A();
echo $text->get_text();
?>
我在这里得到了一堆错误:
警告:正在从中的空值创建默认对象C: ''axamplep''htdocs''fw''A.class.php在第9行
注意:正在尝试获取中非对象的属性C: 第24行上的''axamplep''htdocs''fw''A.class.php
致命错误:对中的非对象调用成员函数test_model()C: 第24行上的''axamplep''htdocs''fw''A.class.php
我做错了什么?谢谢你的小费!
p.S.加载的文件中没有太多:
<?php
class Test {
public function test_model()
{
return 'testmodel';
}
}
?>
在A类的构造函数中,您没有将"已加载"的模型分配给任何对象,后来您试图使用没有分配给它的$model属性。
试试这个:
class A {
public $load;
public $model;
public $text;
public function __construct()
{
$this->load = new Loader();
$this->model = $this->load->model('Test');
$this->text = $this->model->test_model();
}
(…)
问题可能是您没有将Loader.model定义为对象,而是按原样处理它。
class Loader {
public $model = new stdClass();
public function model($model)
{
require_once("models/" . $model . ".php");
return $this->model->$model = new $model();
}
}
当你有这样的课程时,你可以使用
$this->model->model_name->model_method();
$this->model = $this->load->model('Test')
,请尝试以下代码(UPDATED)。
您可以简单地通过调用$this->loadModel(MODEL)
函数来加载模型
<?php
error_reporting(E_ALL);
class Loader {
private $models = null;
public function model($model)
{
require_once("models/" . $model . ".php");
if(is_null($this->models)){
$this->models = new stdClass();
}
$this->models->$model = new $model();
return $this->models;
}
}
class A{
public $load;
public $model;
public $text;
public function __construct()
{
$this->load = new Loader();
$this->loadModel('Test');
$this->loadModel('Test2');
$this->text = $this->model->Test2->test_model();
}
public function get_text()
{
return $this->text;
}
private function loadModel($class){
$this->model = $this->load->model($class);
}
}
$text = new A();
echo $text->get_text();
?>