簡體   English   中英

為什么沒有加載php類

[英]why is php class not being loaded

我測試這個東西,我正在嘗試加載一個類,並使用它像這樣:

$這 - >模型 - > 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();

?>

我在這里收到一堆錯誤:

警告:在第9行的C:\\ xampp \\ htdocs \\ fw \\ A.class.php中從空值創建默認對象

注意:嘗試在第24行的C:\\ xampp \\ htdocs \\ fw \\ A.class.php中獲取非對象的屬性

致命錯誤:在第24行的C:\\ xampp \\ htdocs \\ fw \\ A.class.php中的非對象上調用成員函數test_model()

我究竟做錯了什么? 謝謝你的提示!

在加載的文件中PS不多:

<?php

class Test {

    public function test_model()
    {
        return 'testmodel';
    }
}

?>

如果要在構造函數中避免使用$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();

?>

在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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM