PHP/Class/ get

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

Enforcing property access using magic accessor methods

   <source lang="html4strict">

<? class Person {

   protected $__data = array("person", "email");
   public function __get($property) {
       if (isset($this->__data[$property])) {
           return $this->__data[$property];
       } else {
           return false;
       }
   }
   public function __set($property, $value) {
       if (isset($this->__data[$property])) {
           return $this->__data[$property] = $value;
       } else {
           return false;
       }
   }

} ?>

 </source>
   
  


__get( ) specifies what to do if an unknown property is read from within your script

   <source lang="html4strict">

<?

   class Dog {
           public $Name;
           public $DogTag;
 
           public function __get($var) {
                   print "Attempted to retrieve $var and failed...\n";
           }
   }
   $poppy = new Dog;
   print $poppy->Age;

?>

 </source>
   
  


Intercepting Property Access with __get() and __set() (PHP 5 Only)

   <source lang="html4strict">

<?php class TimeThing {

 function __get( $arg ) {
   if ( $arg == "time" ) {
     return getdate();
   }
 }
 function __set( $arg, $val ) {
   if ( $arg == "time" ) {
     trigger_error( "cannot set property $arg" );
     return false;
   }
 }

} $cal = new TimeThing(); print $cal->time["mday"]."/"; print $cal->time["mon"]."/"; print $cal->time["year"]; ?>

 </source>