PHP/Class/Reflection Existance

Материал из Web эксперт
Версия от 10:00, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

class_exists: given a class name and check its existance

   <source lang="html4strict">

<?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(); ?>

      </source>
   
  


Define class helper class to check the method existance

   <source lang="html4strict">

<?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() ); ?>


      </source>