潜在的PHP内存是否存在?

时间:2011-01-02 15:11:49

标签: php design-patterns memory-leaks classloader

嘿,我需要建议。这个小功能我写的“好”还是会成为一种资源匮乏? 它以下列方式使用:

$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;  }

我担心这种方法效果不佳,会消耗太多内存,或者我错了?对此有更好的做法吗?

3 个答案:

答案 0 :(得分:1)

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

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

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

最后 - php有一个名为autoload的功能,如果尚未定义,它将从文件中加载一个类。你应该加入这个而不是把逻辑放在你的注册表中。

答案 1 :(得分:0)

我没有在你的代码中看到任何内存占用的东西..如果你经历任何这样的事情。它可能是你要加载的课程

答案 2 :(得分:0)

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

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