Check whether instance of a class exists, if not create an instance

a 夏天 提交于 2019-12-04 03:23:52

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.

PHP has a function called class_exists($class_name), returns a bool.

http://www.php.net/manual/en/function.class-exists.php

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");
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!