【问题标题】:How can I access the same name method in the parent class?如何访问父类中的同名方法?
【发布时间】:2017-07-02 19:12:24
【问题描述】:

这是我的代码的简化:

class questions {

    public function index( $one = '', $two = '', $three = '' ) {
        return 'sth';
    }
}


class tags extends questions {

    public function index () {
        return parentClass::index();
    }

}

但是我的代码抛出了这个错误:

有人知道我该如何解决这个错误吗?

expected result is printing: sth

【问题讨论】:

  • 检查autoloader.php中的代码...
  • 您应该使用 parent::index()tags 类调用 questions::index() 而不是 parentClass::index()
  • 你试过return questions::index();
  • 您的代码中没有parentClass。访问父母有一个关键字parent
  • @Jocelyn <?php function my_autoloader($class) { require_once($class.".php"); } spl_autoload_register('my_autoloader'); ?>。你知道它有什么问题吗?

标签: php function class oop inheritance


【解决方案1】:

如果你扩展一个类并覆盖一个方法,你必须确保被覆盖的方法具有相同的“原型”,即,它必须具有相同数量的方法参数且顺序相同。这就是您收到第一个警告的原因:

警告:tags::index() 的声明应与 C:\xampp\htdocs\ 中的 questions::index($query_where = '', $query_join = '', $call_from = NULL) 兼容myweb\others\tags.php3

其次,如果要从父类中调用同名函数,则需要使用parent关键字:

class tags extends questions {

    public function index ($query_where = '', $query_join = '', $called_from = NULL) {
        return parent::index($query_where, $query_join, $called_from);
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    相关资源
    最近更新 更多