PHP/Class/Reflection Existance
class_exists: given a class name and check its existance
<?php
class Person {
private $name;
private $age;
private $id;
function setId( $id ) {
$this->id = $id;
}
function getId(){
echo "get id method";
}
function __clone() {
$this->id = 0;
}
}
$classname = "Person";
if ( ! class_exists( $classname ) ) {
throw new Exception( "No such class as $classname" );
}
$myObj = new $classname();
$myObj->getId();
?>
Define class helper class to check the method existance
<?php
class A {
function getA( ) {
return array( "A", "B" );
}
}
class Helper {
private $classA;
function __construct( A $classA ) {
$this->classA = $classA;
}
function __call( $method, $args ) {
if ( method_exists( $this->classA, $method ) ) {
return $this->classA->$method( );
}
}
}
$tool= new Helper( new A() );
print_r( $tool->getA() );
?>