为什么将函数转换为父方法将被声明两次?

时间:2017-07-02 20:01:58

标签: php function class oop inheritance

Here简化了我的代码:

<?php

class questions {

    public function index( $from = null ) {

        if ( $from != 'test' ) {
            return $this->test();
        }

        return 'sth';
    }

    public function test(){

        function myfunc(){}

        return $this->index(__FUNCTION__);
    }
}


class tags extends questions {

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

}

$obj = new tags;
echo $obj->index();

正如你在小提琴中所看到的那样,它会抛出这个错误:

  

警告:标签:: index()的声明应与第29行/ in / Y5KVq中的问题:: index($ from = NULL)兼容

     

致命错误:无法在第16行的/ in / Y5KVq中重新声明myfunc()(先前在/ in / Y5KVq:16中声明)

     

使用代码255退出流程

为什么呢?自然myfunc()应该声明一次。由于test()将被调用一次。那么错误说的是什么?

无论如何,我该如何解决?

1 个答案:

答案 0 :(得分:4)

问题是$objtags的实例,tags::index()没有$from参数。

所以在这里,当你致电$obj->index()时会发生什么:

  1. tags::index()在没有任何参数的情况下调用parent::index()questions::index())。
  2. questions::index()未收到任何参数,因此$fromNULL
  3. 由于$from不等于'test',因此会调用$this->test()。请记住,就PHP而言,$this是指$obj,因此是tags的实例。所以questions::index()实际上是在这里调用tags::test()
  4. tags::test()不存在,因此会调用questions::test()
  5. questions::test()定义函数myfunc()并返回$this->index(),其中包含当前函数的名称('test')。同样,请记住,就PHP而言,$this是指$obj,因此questions::test()实际上是在这里调用tags::index()
  6. tags::index()不接受任何参数,并且在没有任何参数的情况下调用parent::index()(或questions::index()
  7. 由于questions::index()test::index()调用而没有任何参数,$from再一次NULL,我们最终会陷入一个崩溃的循环,因为函数{{1}现在已经定义了。
  8. 如果您删除myfunc()函数声明,则会发现您最终处于无限循环中。

    更改myfunc()以接受传递给test::index()的{​​{1}}参数将使此代码按您希望的方式运行:

    $from