Я тестирую эту вещь, где я пытаюсь загрузить класс и использовать его следующим образом:
$this-> Модель → 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:\xampp\htdocs\fw\A.class.php в строке 9
Примечание. Попытка получить свойство не-объекта в C:\xampp\htdocs\fw\A.class.php в строке 24
Неустранимая ошибка: вызов функции-члена test_model() для не-объекта в C:\xampp\htdocs\fw\A.class.php в строке 24
Что я делаю не так? Спасибо за любой отзыв!
PS не много в загруженном файле:
<?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();
}
(...)
Попробуйте использовать следующий код (ОБНОВЛЕНО), если вы хотите избежать $this->model = $this->load->model('Test')
в конструкторе.
Вы можете просто загрузить модели, вызвав $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();
?>
Проблема может заключаться в том, что вы не определили 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();