PHP/Class/Reflection Invoke
__call: invoke class method dynamically
<?php
class A {
function getA( ) {
return array( "A", "B" );
}
function setA( $country, $district ) {
return "$country, $district\n";
}
}
class Helper {
private $classA;
function __construct( A $classA ) {
$this->classA = $classA;
}
function __call( $method, $args ) {
if ( method_exists( $this->classA, $method ) ) {
return call_user_func_array(array( $this->classA, $method ), $args );
}
}
}
$tool= new Helper( new A() );
print_r( $tool->setA( "UK", "BN" ) );
?>
call_user_func: invoke class method and pass parameters
<?php
class Person {
private $name;
private $age;
private $id;
function __construct( $name, $age ) {
$this->name = $name;
$this->age = $age;
}
function setId( $id ) {
$this->id = $id;
}
function getId(){
echo $this->id;
}
function __clone() {
$this->id = 0;
}
}
$p = new Person("A",10);
call_user_func( array( $p, "setId" ), 20 );
$p->getId();
?>