php - 访问兄弟类方法

标签 php oop class visibility siblings

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

fatal error :第 5 行在 Router.php 中的非对象上调用成员函数 run()

我做错了什么?

核心:

<?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();
    }
}

Controller :

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;
}

提前致谢。

最佳答案

如果您展开扩展以查看它的实际外观,您就会明白它失败的原因:

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(); 来引用父类

关于php - 访问兄弟类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304923/

相关文章:

php - 如何从多个查询中获取多个结果

php - 通过 laravel 框架集成现有项目?

c# - 将参数中的字段传递给外部方法调用是否违反了开放/封闭原则?

PHP动态类加载

php - 从抽象类中的静态函数获取类名

php - 在公开 ID 上发送用户/通过帖子

php - 如何卸载 pear 包?

javascript - 面向对象的 JavaScript : Usage of "this" necessary within methods?

java - 传递和返回没有 "new"关键字的类对象

c++ - 这是类模板的全部或部分特化吗?