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()
将被调用一次。那么错误说的是什么?
无论如何,我该如何解决?
答案 0 :(得分:4)
问题是$obj
是tags
的实例,tags::index()
没有$from
参数。
所以在这里,当你致电$obj->index()
时会发生什么:
tags::index()
在没有任何参数的情况下调用parent::index()
(questions::index()
)。questions::index()
未收到任何参数,因此$from
为NULL
$from
不等于'test'
,因此会调用$this->test()
。请记住,就PHP而言,$this
是指$obj
,因此是tags
的实例。所以questions::index()
实际上是在这里调用tags::test()
。tags::test()
不存在,因此会调用questions::test()
。questions::test()
定义函数myfunc()
并返回$this->index()
,其中包含当前函数的名称('test'
)。同样,请记住,就PHP而言,$this
是指$obj
,因此questions::test()
实际上是在这里调用tags::index()
。tags::index()
不接受任何参数,并且在没有任何参数的情况下调用parent::index()
(或questions::index()
。questions::index()
从test::index()
调用而没有任何参数,$from
再一次NULL
,我们最终会陷入一个崩溃的循环,因为函数{{1}现在已经定义了。如果您删除myfunc()
函数声明,则会发现您最终处于无限循环中。
更改myfunc()
以接受传递给test::index()
的{{1}}参数将使此代码按您希望的方式运行:
$from