Anonymous class construct

I need the idea of ​​creating an anonymous class in PHP. I do not know how I can work.

See my limitations :

  • In PHP, you cannot create an anonymous class, for example an anonymous function (for example, class {} );
  • In PHP, you do not have the scope of the class (except for namespaces, but it has the same problem below);
  • In PHP, you cannot use variables to indicate the name of a class (for example, class $name {} );
  • I do not have access to install runkit PECL.

What do I need and why :

Well, I need to create a function called create_class() that gets the key name and an anonymous class. This will be useful to me because I want to use different characters of the name class that PHP cannot accept. For example:

 <?php create_class('it.is.an.example', function() { return class { ... } }); $obj = create_object('it.is.an.example'); ?> 

So, I need an idea that allows this use. I need this because in my framework I have this path: /modules/site/_login/models/path/to/model.php . So, model.php needs to declare a new class called site.login/path.to.model .

When create_object() called, if the internal cache has the definition of $class (for example, it.is.an.example ), it simply returns a new class object. If not, download. Therefore, I will use the content of $class to quickly find out what the class file is.

+7
source share
4 answers

In PHP 7.0 there will be anonymous classes . I do not 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 the object with the type of the anonymous class and register it with $repository . To get the object, you use the key that you created with: $repository['it.is.an.example'] .

+4
source

You can create a dummy class using stdClass

 $the_obj = new stdClass(); 
+6
source

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 cache inside to check for duplicates

+6
source

If you really need to do this, you can use eval()

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

But the gods will not approve of this. You will go to hell if you do.

0
source

All Articles