PHP/Class/Reflection Invoke — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 10:00, 26 мая 2010

__call: invoke class method dynamically

   <source lang="html4strict">

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

      </source>
   
  


call_user_func: invoke class method and pass parameters

   <source lang="html4strict">

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

      </source>