Anonymous class construction

旧城冷巷雨未停 提交于 2019-12-05 02:51:49

In PHP 7.0 there will be anonymous classes. I don't fully understand your question, but your create_class() function might look like this:

function create_class(string $key, array &$repository) {
    $obj = new class($key) {
        private $key;
        function __construct($key) {
            $this->key = $key;
        }
    };
    $repository[$key] = $obj;
    return $obj;
}

This will instantiate an object with an anonymous class type and register it into the $repository. To get an object out you use the key you created it with: $repository['it.is.an.example'].

You can create a dummy class using stdClass

$the_obj = new stdClass();

So basically you want to implement a factory pattern.

Class Factory() {
  static $cache = array();

  public static getClass($class, Array $params = null) {
    // Need to include the inc or php file in order to create the class
    if (array_key_exists($class, self::$cache) {
      throw new Exception("Class already exists");
    }

    self::$cache[$class] = $class;
    return new $class($params);
  }
}

public youClass1() {
  public __construct(Array $params = null) {
     ...
  }
}

Add a cache within to check for duplicates

If you really need to to that, you could use eval()

$code = "class {$className} { ... }";
eval($code);
$obj = new $className ();

But the gods won't approve this. You will go to hell if you do it.

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