调用未定义的方法stdClass :: show()

时间:2018-04-03 21:29:02

标签: php

过去几个小时我一直绞尽脑汁想弄清楚为什么我会遇到这个错误。你知道他们说什么,谷歌失败时,Stack Overflow。感谢任何和所有的帮助,我的头痛会感谢你。 :)

错误消息

Error: Call to undefined method stdClass::show() in /application/controllers/Dashboard.php:10
Stack trace:
#0 /system/Router.php(41): Dashboard->index()
#1 /index.php(39): CP_Router->loader()
#2 {main}

index.php - 负责引导系统。

define('CPBASE', realpath(dirname(__FILE__)) . '/');
require_once(CPBASE . 'system/Controller.php');
require_once(CPBASE . 'system/Registry.php');
require_once(CPBASE . 'system/Router.php');
require_once(CPBASE . 'system/View.php');

function __autoload($class_name) {
    $filename = strtolower($class_name) . '.php';
    $file = __SITE_PATH . '/model/' . $filename;

    if (file_exists($file) == false)
    {
        return false;
    }
    include ($file);
}

$registry = new CP_Registry();
$registry->router = new CP_Router($registry);
$registry->router->setPath(CPBASE . 'application/controllers');
$registry->view = new CP_View($registry);
$registry->router->loader();

view.php - 负责生成输出。

class CP_View {
    private $registry;
    private $vars;

    function __construct($registry){
        $this->registry = $registry;
    }

    public function __set($key, $value){
        $this->vars[$key] = $value;
    }

    function show($name){
        $path = CPBASE . 'views/' . $name . '.php';

        if(file_exists($path) == false){
            throw new Exception('View not found: ' . $path);
            return false; 
        }

        foreach($this->vars as $key => $value){
            $$key = $value;
        }

        include($path);
    }
}

dashboard.php - 调用视图的控制器。

注意: $ this->注册表通过CP_Controller传递给Dashboard控制器。

<?php

class Dashboard extends CP_Controller {
    function __construct(){

    }

    public function index(){
        $this->registry->view->title = 'CPMVC';
        $this->registry->view->show('index');
    }   
}

1 个答案:

答案 0 :(得分:0)

我相信这就是错误的来源:

  1. $this->registry->view未设置,因此最初为null
  2. 您为它分配了一个对象($this->registry->view->title = 'CPMVC';),因此PHP会为您创建一个stdClass对象
  3. 您尝试在此对象上调用方法show,但stdClass对象没有方法。
  4. 根本原因是$this->registry本身没有被分配(例如,您错过了对parent::_construct的调用,这会设置它,或者您已标记它{ {1}}而不是private);或者注册表对象没有protected属性(完全可能,因为您还没有显示该代码)。