dongxing8009 2013-02-08 15:21
浏览 14
已采纳

PHP类函数声明问题

i have an issue with function redeclaration problem. So, i am trying to call multiple times this example.

class myClass {

    function abc() {

        function internal() {

        return "i am internal"; 
        }

    return internal();
    }

}


$myClass = new myClass();

echo $myClass->abc();
echo $myClass->abc(); // HERE IS THE PROBLEM when i call same function second time

PHP showing Fatal error: Cannot redeclare internal() (previously declared).

Does anyone have an idea how can i solve this issue?

Thanks in advance.

  • 写回答

4条回答 默认 最新

  • duandu1049 2013-02-08 15:28
    关注

    When you declare a function using function <name>(), you are not declaring it in the scope you think you are. That function is being declared in the class global scope, not the function/class scope.

    See the PHP Docs: http://www.php.net/manual/en/functions.user-defined.php#example-149

    So, when you call abc, you are re-declaring the global function, internal.

    If you want to do what you are doing, you can use closures instead (NOTE: This only works in PHP 5.3+). This has the benefit of being able to read local variables from within abc (if you use the use keyword).

    class myClass {
    
        function abc() {
            $internal = function() {
                return "i am internal"; 
            };
    
            return $internal();
        }
    }
    

    You can also declare internal as a private function of the class, especially if it's not going to change. Why keep re-making a function?

    class myClass {
    
        private function internal(){
            return "i am internal"; 
        }
    
        function abc() {
            return $this->internal();
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据