【问题标题】:Access Sibling Class Method访问同级类方法
【发布时间】:2013-04-24 16:05:15
【问题描述】:

我正在做一个基本的 MVC 练习,但我收到了这个错误:

Fatal error: Call to a member function run() on a non-object in Router.php on line 5

我做错了什么?

核心:

<?php

class Core {
    protected $router;
    protected $controller;

    public function run() {
        $this->router =& load_class('Router');
        $this->controller =& load_class('Controller');

        $this->router->run();
    }
}

路由器:

class Router extends Core {
    public function run() {
        echo $this->controller->run();
    }
}

控制器:

class Controller extends Core {
    public function run() {
        return 'controller';
    }
}

哦,还有 load_class 函数

function &load_class($class_name) {
    $path = ROOT . 'system/classes/' . $class_name . '.php';

    if (file_exists($path)) {
        include_once($path);

        if (class_exists($class_name)) {
            $instance = new $class_name;
            return $instance;
        }
    }

    return false;
}

非常感谢。

【问题讨论】:

  • 你是如何运行代码的?
  • var_dump($this-&gt;controller) 显示什么?
  • @Barmar 它什么也没显示。
  • @Raidenace 我正在调用 $core->run()
  • 错误发生在哪一行?

标签: php oop class visibility siblings


【解决方案1】:

如果您展开扩展以查看它的实际外观,您将了解它失败的原因:

class Core {
    protected $router;
    protected $controller;

    public function run() {
        $this->router =& load_class('Router');
        $this->controller =& load_class('Controller');

        $this->router->run();
    }
}

结束:

class Router extends Core {
    public function run() {

        echo $this->controller->run();
    }
}

大致等同于:

class Router {
    protected $router;
    protected $controller;   // <- this is "$this->controller"

    public function run() {

        echo $this->controller->run();
    }
}

你可以看到 $this->controller 是一个变量所以没有方法

因此,在扩展版本中,您需要使用 parent::$controller->run(); 来引用父类;

【讨论】:

    【解决方案2】:

    我可能在这里偏离了基础,但是通过在每个类中扩展 Core,我认为您无意中覆盖了 run() 方法并混淆了每个类的范围。您是否尝试过从单独的非扩展类调用 run()?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多