I got a way to define nested classes in Php, but it is pretty raw.
class foo {
function define_new_class($class, $code) {
if (!class_exists($class)) {
$definition = eval($code);
}
}
function bar() {
$new_class = "boo";
$this->define_new_class($new_class, "class $new_class {}");
$obj = new $new_class();
echo "Current class: " . get_class($this) . "
"; // foo
echo "\$obj class: " . get_class($obj) . "
"; // boo
}
}
$foo = new foo();
$foo->bar();
Is it possible to do the same job in a gracefully way?
Since there is no way to define a true nested classes: instead of use a nested class you can create another class that starts with the name of OuterClass:
class OuterClass {
...stufs...
}
class OuterClass_InnerClass {
...stufs...
}
or use namespaces
class OuterClass {
...stufs...
}
class \OuterClass\InnerClass {
...stufs...
}