【问题标题】:A potential PHP memory hog or not?是否是潜在的 PHP 内存占用者?
【发布时间】:2011-01-02 15:11:49
【问题描述】:

嘿,我需要建议。我写的这个小函数是“好”还是会占用资源? 它的使用方式如下:

$login = load_class('LoginClass');

load_class('LoginClassTwo', false); // for singletons and stuff
$loginTwo = LoginClassTwo::getInstance();

这是函数

function load_class($class, $instantiate = TRUE){

static $obj = array(); // holds the instancec of the classes

$l = strtolower($class); // the name of the file is the name of the class but lowercased

if (isSet($obj[$l])) { // Do we have an instance?

    return $obj[$l]; 
}

$file = 'classess/' . $l . '.class.php';
if (file_exists($file) && is_readable($file)) { // Can we read the file?

    include $file;

    if ($instantiate == FALSE) { // Do we need to instantiate?

        $obj[$l] = TRUE;
    } else {

        $obj[$l] = new $class;
    }

    return $obj[$l];
}

return FALSE;  }

我担心这种方法无效并且会消耗太多内存还是我错了?有没有更好的做法?

【问题讨论】:

    标签: php design-patterns memory-leaks classloader


    【解决方案1】:

    这是一种常见的模式,称为注册表或服务定位器。

    可能对象的全局注册表存在问题,因为这些对象在脚本结束之前不会被回收。如果其中一个对象使用大量内存,那么就可以了。然而,就其本身而言,这不是问题,记忆明智。

    您应该考虑要全局保留哪些对象。全局对象有助于程序的整体复杂性和耦合,这是一种普遍接受的真理。也许您可以将其中一些作为参数传递给构造函数,而不是全局寻址?当然,这完全取决于用例。

    最后 - php 有一个名为autoload 的功能,如果它尚未定义,它将从文件中加载一个类。您应该对此进行挂钩,而不是将逻辑放入注册表中。

    【讨论】:

    • 感谢您的信息。我想我会写一个完整的注册表类来保存我的类实例。今晚我会在这里发布。
    【解决方案2】:

    我在您的代码中没有看到任何占用内存的东西。如果您遇到任何这样的事情。它可能是你正在加载的类

    【讨论】:

    • 我问的是有没有这种可能,不是代码本身会泄露;)
    【解决方案3】:

    PHP 有一个用于类的本机 __autoload 函数。每当您尝试从尚不存在的类创建新对象时,它都会运行。该函数将尝试包含一个使用类名作为类文件的类文件。这就是为什么许多项目每个类使用一个文件的原因。这样你就不需要再次手动加载一个类,除非需要,类永远不会被加载。请参阅以下链接。

    http://www.php.net/manual/en/language.oop5.autoload.php

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 2016-03-05
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 2017-11-25
      • 2012-06-25
      相关资源
      最近更新 更多