检查一个类的实例是否存在,如果不存在则创建一个实例 [英] Check whether instance of a class exists, if not create an instance
问题描述
我想知道是否可以创建一个函数并将其传递给一个类名.然后,该函数检查该类的实例当前是否存在,如果不存在,则创建该类的实例.此外,如果可能,请将该变量设置为全局变量,并要求将其返回.我意识到返回可能是唯一的选择.
I was wondering if it's possible to create a function and pass it a class name. The function then checks if an instance of the class currently exists, if it does not it create an instance of the class. Furthermore if possible make that variable global and require it to be returned. I realize that returning may be the only option.
function ($class_name) {
// Check if Exists
// __autoload will automatically include the file
// If it does not create a variable where the say '$people = new people();'
$class_name = new $class_name();
// Then if possible make this variable a globally accessible var.
}
这可能还是我疯了?
推荐答案
eval
几乎是实现此目的的唯一方法.确保由用户输入(例如来自$_GET
或$_POST
值的输入)未提供此功能非常重要.
eval
is pretty much the only way to do this. It is very important you make sure this isn't provided by user input, like from $_GET
or $_POST
values.
function create_or_return($class_name) {
if(! class_exists($class_name)) {
eval("class $class_name { }");
// put it in the global scope
$GLOBALS[$class_name] = new $class_name;
}
}
create_or_return("Hello");
var_dump($GLOBALS['Hello']);
/*
class Hello#1 (0) {
}
*/
您无法真正使它在全球范围内可访问,因为PHP没有像javascript这样的全局对象.但是,您不能简单地创建一个容纳对象的容器.
You can't really make it globally accessible because PHP doesn't have a global object like javascript does. But you can't simply make a container holding the object.
这篇关于检查一个类的实例是否存在,如果不存在则创建一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!