Вызов функции-члена для необъекта - PullRequest
3 голосов
/ 11 февраля 2011

У меня есть шаблонный класс, который может анализировать переменные массива в файлах TPL или просто отображать чистый HTML-файл. Функция разбора работает нормально, но функция отображения возвращает следующую ошибку:

"Неустранимая ошибка: вызов функции-члена display () для необъекта в C: \ xampp \ htdocs \ clancms \ controllers \ home.php в строке 7"

Это home.php

class Home extends Controller {

    function index(){

        echo $this->template->display('index_body.tpl');
    }

}

Это шаблон класса

class Template {

    var $file = '';
    var $vars = '';
    var $themeID = '';
    var $themeTitle = '';
    var $themeDescription = '';
    var $themePath = '';


    function getTheme(){

        if($_SESSION['memberid'] != NULL){

            $query = "
                SELECT memberid, themeid
                FROM members
                WHERE memberID = '".$_SESSION['memberID']."
                LIMIT 1";

            if($query = mysql_query($query)){
                $member = mysql_fetch_assoc($query);


                $query = "
                    SELECT themeID, themeTitle, themeDescription, themePath
                    FROM {DB_PREF} 
                    WHERE themeID = ".$member['themeID']."
                    LIMIT 1";

                if($query = mysql_query($query)){
                    $theme = mysql_fetch_assoc($query);
                    $this->themeID = $theme['themeID'];
                    $this->themePath = BASE_PATH.'/templates/'.$theme['themePath'];
                    $this->themeTitle = $theme['themeTitle'];
                    $this->themeDescription = nl2br(htmlspecialchars($theme['themeDescription']));
                } else {
                    $this->themePath = BASE_PATH.'/templates/default';
                }

            } else {
                $this->themePath = BASE_PATH.'/templates/default';
            }

        } else {
            $this->themePath = BASE_PATH.'/templates/default';
        }

    }

    function parse($file, $vars){

    $this->getTheme();

        if(file_exists($this->themePath.'/'.$file)){
            $file = file_get_contents($this->themePath.'/'.$file);

            foreach($vars as $key => $val){
                $file = str_replace('{'.$key.'}', $val, $file);
            }
            echo $file;
        } else {
            die('Template parser error: the file \''.$this->themePath.'/'.$file.'\' does not exist!');
        }
    }

    function display($file){

        if(file_exists($this->themePath.'/'.$file)){
            $file = file_get_contents($this->themePath.'/'.$file);
            echo $file;
        } else {
            die('Template parser error: the file \''.$this->themePath.'/'.$file.'\' does not exist!');
        }

    }
}

Обновление

Извините, я забыл включить это

<?php

class Controller {

    function Controller(){

        $this->initialize();

    }

    function initialize(){

        $classes = array(
                        'load' => 'Load',
                        'uri' => 'URI',
                        'config' => 'Config',
                        'template' => 'Template'
                        );

        foreach($classes as $var => $class){

            if(file_exists($this->app_path.'/classes/'.$class.'.php')){
                require_once(BASE_PATH.'/classes/'.$class.'.php');
                $this->$var =& new $class;
            } else {
                return FALSE;
            }

        }

    }

}

?>

Ответы [ 2 ]

1 голос
/ 11 февраля 2011

Переменная-член $ template на вашем домашнем экземпляре не инициализируется.Где-то должен быть вызов $this->template = new Template(); или что-то эквивалентное.

Это, вероятно, должно быть в Home __construct или в родительском классе Controller.

Основываясь на функции инициализации вашего контроллера, ябудет предполагать, что файл не существует для одного из заданных классов, и поэтому он рано выходит из функции с return false;

Выводит эхом загружаемые классы, и я был бы удивлен, если бы он его сделалдо конца массива.

0 голосов
/ 11 февраля 2011

должно быть

function index(){

    echo $this->display('index_body.tpl');
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...