我想知道是否可以创建一个函数并向它传递一个类名。然后该函数检查该类的实例当前是否存在,如果不存在,则创建该类的实例。此外,如果可能的话,使该变量成为全局变量并要求返回它。我意识到返回可能是唯一的选择。
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
值,这一点非常重要。
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 那样的全局对象。但是你不能简单地制作一个容器来容纳物体。
关于php - 检查一个类的实例是否存在,如果不存在则创建一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23160509/