问题
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.
}
Is this possible or am I being crazy?
回答1:
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) {
}
*/
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.
回答2:
PHP has a function called class_exists($class_name), returns a bool.
http://www.php.net/manual/en/function.class-exists.php
回答3:
Something along the lines of:
function some_fumction($class_name) {
if(class_exists($class_name)) {
return new $class_name;
} else {
throw new Exception("The class $class_name does not exist");
}
}
来源:https://stackoverflow.com/questions/23160509/check-whether-instance-of-a-class-exists-if-not-create-an-instance