问题
I need an idea to create anonymous class on PHP. I don't know how I can works.
See my limitations:
- On PHP you can't make anonymous class, like anonymous function (like
class {}
); - On PHP you don't have class scope (except in namespaces, but it have the same problem below);
- On PHP you can't use variables to specify the class name (like
class $name {}
); - I don't have access to install the
runkit
PECL.
What I need, and why:
Well, I need create a function called ie create_class()
that receives a key name and a anonymous class. It'll be useful for me because I want use different name class symbols that PHP can't accept. For instance:
<?php
create_class('it.is.an.example', function() {
return class { ... }
});
$obj = create_object('it.is.an.example');
?>
So, I need an idea that accept this use. I need it because on my framework I have this path: /modules/site/_login/models/path/to/model.php
. So, the model.php
need to declare a new class called site.login/path.to.model
.
On call create_object()
if the internal cache have a $class
definition (like it.is.an.example
it simply return the new class object. If not, need load. So I will use the $class
content to search fastly what is the class file.
回答1:
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']
.
回答2:
You can create a dummy class using stdClass
$the_obj = new stdClass();
回答3:
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
回答4:
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.
来源:https://stackoverflow.com/questions/9726396/anonymous-class-construction