2017-07-02 16 views
1

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

正如您在拨弄看到,它抛出这个错误:

Warning: Declaration of tags::index() should be compatible with questions::index($from = NULL) in /in/Y5KVq on line 29

Fatal error: Cannot redeclare myfunc() (previously declared in /in/Y5KVq:16) in /in/Y5KVq on line 16

Process exited with code 255

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

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

+0

。如果您要在可能运行多次的代码中动态声明它,您应该将其包装在'if(!function_exists('myfunc'))'检查中。 – rickdenhaan

+0

@rickdenhaan是的,我可以做你检查你提到的。但是我想知道为什么这个函数会被执行多次?代码将如何编译? –

回答

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,我们最终在一个循环崩溃,因为函数myfunc()是现在已经定义。

如果删除myfunc()函数声明,你会看到在一个无限循环结束了。

更改test::index()接受它传递给parent::index()一个$from参数将使这个代码的工作,你所希望的方式:你只能一次声明函数

class tags extends questions { 

    public function index ($from = null) { 
     return parent::index($from); 
    } 

} 
+0

谢谢你..伟大的分析。你能告诉我最后一段的例子吗? –

+0

当然,我已经更新了我的答案。 – rickdenhaan

+0

而我的最后一个问题:你知道我该如何处理'$ other_arg'?预期的输出是'sth'。 https://3v4l.org/pIEr7 –

相关问题