3

我试图了解 CodeIgniter 中的框架结构,而我刚刚开始并想出了这个小误解。

所以有人可以帮我理解以下内容:-

1-为什么他们使用引用来传递类的实例......我的意思是为什么不只是一个简单的变量?

2-以及为什么该函数将类的名称存储在数组中而不是“字符串变量”中(请不要将我的 php 术语判断为我最擅长它)..?!

static $_classes = array();
                   ^^^^^^^ this cloud be just ("") or am i missing something

这是功能,所以你不会去寻找它。

function &load_class($class, $directory = 'libraries', $prefix = 'CI_')
    {
        static $_classes = array();

        // Does the class exist?  If so, we're done...
        if (isset($_classes[$class]))
        {
            return $_classes[$class];
        }

        $name = FALSE;

        // Look for the class first in the local application/libraries folder
        // then in the native system/libraries folder
        foreach (array(APPPATH, BASEPATH) as $path)
        {
            if (file_exists($path.$directory.'/'.$class.'.php'))
            {
                $name = $prefix.$class;

                if (class_exists($name) === FALSE)
                {
                    require($path.$directory.'/'.$class.'.php');
                }

                break;
            }
        }

        // Is the request a class extension?  If so we load it too
        if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
        {
            $name = config_item('subclass_prefix').$class;

            if (class_exists($name) === FALSE)
            {
                require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php');
            }
        }

        // Did we find the class?
        if ($name === FALSE)
        {
            // Note: We use exit() rather then show_error() in order to avoid a
            // self-referencing loop with the Excptions class
            exit('Unable to locate the specified class: '.$class.'.php');
        }

        // Keep track of what we just loaded
        is_loaded($class);

        $_classes[$class] = new $name();
        return $_classes[$class];
    }
4

2 回答 2

7

关键是static之前的关键字$_classes = array();。这使得$_classes数组在多次调用函数之间保持它的值。基本上,他们将其用作实例化类的本地缓存。为此,字符串不起作用。

请参阅手册中有关 static 关键字的更多信息。

至于返回的参考,我认为那是 php4 的包袱,直到 2.x,php4 才支持 CI。您可能会发现这篇博文有助于了解从 php4 到 php5 的变化。

于 2012-08-18T11:44:59.597 回答
1

传递一个普通(非引用)变量“似乎”是有效的,因为每次传递它时,前一个实例都会被覆盖,最后一个或最新的实例会取而代之。所以每次你创建一个新的类实例。但这很浪费,原因有两个……

  1. 它会创建一个新的实例变量,而不会取消设置前一个实例变量(尽管 PHP 最终会垃圾收集这些变量),从而避免被一些恶意代码读取并在您必须付费的宝贵服务器空间中浪费一些字节的风险为了。

  2. 一个实例意味着一个状态。“输入”状态、“安全”状态、“配置”状态等等。如果您创建一个新变量,您将创建这些状态的副本。如果您随后偶然犯了任何错误,那么您在一个“输入”实例中保存的当前状态可能不会更改以反映当前或最新状态。假设另一个发生了变化;如果你在不同的场合同时使用它们,那么这可能会导致下一步的冲突和灾难。

于 2016-04-26T15:45:40.360 回答