【问题标题】:Why the function into parent method will be declared twice?为什么进入父方法的函数会被声明两次?
【发布时间】:2017-07-02 20:01:57
【问题描述】:

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

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

警告:tags::index() 的声明应该与第 29 行 /in/Y5KVq 中的 questions::index($from = NULL) 兼容

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

进程以代码 255 退出

为什么?当然myfunc() 应该声明一次。因为test() 将被调用一次。那么错误说明了什么?

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

【问题讨论】:

  • 函数只能声明一次。如果您要在可能多次运行的代码中动态声明它,则应将其包装在 if (!function_exists('myfunc')) 检查中。
  • @rickdenhaan 是的,我可以做你提到的检查。但我想知道为什么该函数会被多次执行?代码将如何编译?

标签: php function class oop inheritance


【解决方案1】:

问题在于$objtags 的一个实例,而tags::index() 没有$from 参数。

所以当您致电$obj-&gt;index() 时会发生以下情况:

  1. tags::index() 调用parent::index()(即questions::index())不带任何参数。
  2. questions::index() 不接收任何参数,因此 $fromNULL
  3. 由于$from不等于'test',它调用$this-&gt;test()。请记住,就 PHP 而言,$this 指的是$obj,因此是tags 的一个实例。所以questions::index()实际上是在这里调用tags::test()
  4. tags::test() 不存在,因此调用了 questions::test()
  5. questions::test() 定义函数 myfunc() 并返回 $this-&gt;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() 更改为接受$from 参数,该参数传递给parent::index() 将使此代码按您希望的方式工作:

class tags extends questions {

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

}

【讨论】:

  • 谢谢 .. 很好的分析。你能给我看一个你最后一段的例子吗?
  • 最后一个问题:你知道我该如何处理$other_arg吗?预期输出为sth3v4l.org/pIEr7
  • 好吧,就像警告说的那样:tags::index() 需要与questions::index() 具有相同的参数。所以你还需要在tags::index()的声明中添加$other_problem
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多