【问题标题】:I need help understanding the scope of a function declared inside a class method我需要帮助理解在类方法中声明的函数的范围
【发布时间】:2012-10-14 02:11:24
【问题描述】:

好的,我的面条已经烤了一段时间了。我有一个类,它的方法定义了一个全局可访问的函数。我的问题是:内部类方法如何定义可在全局范围内访问的函数?

这是一个示例:

class MyClass 
{

    // ... accessors, constuctors other methods, et al... 

    // The method in question:
    private function myPrivateMethod()
    {
        if( !function_exists( 'someArbitraryFunction' ) )
        {
            function someArbitraryFunction( $args )
            {
                return "Hello, {$args} world!";
            }
        }            
    } 
}

该类像往常一样在应用程序的早期实例化,但它是在另一个类的方法中实例化的。这是一个浅范围链,但嵌套得足够多,以至于(对我而言)为什么它可以在应用程序之外访问是没有意义的。这违背了我对封装的理解,非常感谢一些见解。

【问题讨论】:

    标签: php scope


    【解决方案1】:

    声明的函数将始终具有全局范围。这不是 JavaScript。

    见:

    class MyClass 
    {
    
        // ... accessors, constuctors other methods, et al... 
    
        // The method in question:
        private function myPrivateMethod()
        {
            if( !function_exists( 'someArbitraryFunction' ) )
            {
                function someArbitraryFunction( $args )
                {
                    return "Hello, {$args} world!";
                }
            }            
        } 
    
        public function run(){
            $this->myPrivateMethod();
        }
    }
    
    var_dump(function_exists('someArbitraryFunction')); // false
    $obj = new MyClass();
    $obj->run();
    var_dump(function_exists('someArbitraryFunction')); // true
    

    作为具有 C/C++ 背景的语言,函数和方法之间有不同的行为。在 PHP 中,函数不服从访问修饰符。

    无论它们在代码中的何处编写,一旦执行通过声明,它就会被定义。

    如果您需要一个函数来遵守作用域,我强烈建议您这样做,因为您可以更好地利用变量的 GC,您可以在 >= PHP 5.3 中使用闭包:

    class MyClass{
    
        private $myArbitraryMethod;
    
        private function myPrivateMethod(){
            $this->myArbitraryMethod = function($args){
    
            }
        }
    
    }
    

    【讨论】:

    • 我刚刚看到了这个related post,从文档来看,这是设计使然...我明白为什么它现在可以工作了,但它似乎是错误的。
    • 不是。只需将函数视为全局函数。如果你需要函数来遵守作用域,我推荐 PHP 5.3 中的闭包。
    • 谢谢,我想这让我大吃一惊。我现在明白了,我可以看到它是如何被快速滥用的。
    • 太棒了!我很高兴你得到澄清。 (:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    相关资源
    最近更新 更多