【问题标题】:How is PHP's Closure scope determined and how does it relate to class declaration?PHP 的 Closure 范围是如何确定的,它与类声明有什么关系?
【发布时间】:2014-08-14 08:38:08
【问题描述】:

我正在尝试在 PHP 中创建私有类。为此,我编写了以下代码:

<?php

$UsesPrivateClass = function () {
    if (!class_exists('PrivateClass', false)) {
        class PrivateClass
        {
            function someUsefulMethod()
            {
                return 1;
            }
        }


        class UsesPrivateClass
        {
            function __construct($needsData)
            {
                $this->privateClass = new PrivateClass();
            }

            function getValue()
            {
                return $this->privateClass->someUsefulMethod() + 1;
            }
        }
    }
    //Return a UsesPrivateClassFactory
    return function ($needsData) {
        return new UsesPrivateClass($needsData);
    };
};
$UsesPrivateClass = $UsesPrivateClass();

//Now you can access the methods and data of the private class, without exposing it to the global object!

$usesPrivateClassInstance = $UsesPrivateClass("data needed");

echo $usesPrivateClassInstance->getValue(); //Prints out 2

$x = new PrivateClass(); //Throws exception

唯一的问题是最后一行$x = new PrivateClass(); //Throws exception 没有抛出异常。我不知道为什么。类声明不是绑定到闭包对象吗?或者这是函数式编程语言和面向对象编程语言(至少,在 PHP 中实现的)之间的粗糙边缘之一?

【问题讨论】:

    标签: php oop functional-programming closures


    【解决方案1】:

    当您定义一个类时,PHP 不关心任何闭包,它始终是全局且公开可用的。

    class PrivateClass {} 的封装方式无关紧要,因此执行UsesPrivateClass() 后的最后一行也不例外。但是,如果您不执行该功能,则该类将不可用。

    【讨论】:

    • 感谢您的解释!
    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 2010-09-18
    • 2010-10-15
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多