PHP : Function Reference : Object Aggregation/Composition Functions : aggregate_methods
a
You can use this to dynamicily add methods to a class
class foo {
function addMethod( $code ) {
$cname = uniqid("class");
eval( "class ${cname} { ${code} }" );
aggregate_methods( $this , $cname );
}
function bar() {
$this->addMethod( "function baz() { echo 'sha'; }" );
}
}
$bang = new foo();
$bang->bar();
$bang->baz();
rodolfo
Just a note: aggregate_methods doesn't aggregate those methods already defined in the class, including those methods inherited from a parent class.
Here's an example:
- If class B inherits from class A and aggregates methods from class C:
<?php
class A {
function foo() {
echo 'from class A';
}
}
class B extends A {
function B() {
aggregate_methods($this,'C');
}
}
class C {
function foo() {
echo 'from class C';
}
}
$myclass = new B();
$myclass->foo();
// This will print 'from class A'
?>
|