RicH and FamouS

       Home         Glosar IT                                                                                                                                                                                                              SUBSCRIBE NOW!
        

05.04.2009

Getter, setter si evenimente in PHP

Pentru folosirea setterilor si getterilor :
- se declara proprietatea private
- se declara o functie cu numele "get".nume_properietate
- se declara o functie cu numele "set".nume_properietate

Pentru folosirea evenimentelor
- se creaza o innstanta a clasei
- evenimentele sunt de forma "on".numefunctie = "nume_functie_utilizator"
- functia trebuie declarata private
- (!) valoarea returnata de eveniment este trimisa ca ultim parametru pentru functie

Cod:

<?php
class TException extends Exception {
public function __construct ( $errorCode, $errorDescription ) {
echo htmlspecialchars("<" . $errorCode . "> " . $errorDescription );
}
}
class generic {
# array cu evenimentele
private $e = array ( );
public function addEventListener ( $property, $value ) {
if ( strpos($property, "on") === FALSE ) throw new
TException("addEventListener", "sintaxa eveniment incorecta : " .
$property );
if ( is_array($value) ) {
$object = each ( $value );
$method = $object["value"];
$object = $object["key"];
if ( ! method_exists($object, $method) ) throw new
TException("addEventListener", "metoda '". $method ."' nu exista (
instanta obiectului : '". $object ." )");
} else if ( ! function_exists($value) ) throw new TException("addEventListener", "functia '". $value ."' nu exista");
$this->e[$property] = $value;
}
//
// removeEventListener ?
//
public function eventExists ( $eventName ) {
return ( isset($this->e[$eventName] ) ) ? 1 : 0;
}
public function getEventListener( $eventName ) {
return $this->e[$eventName];
}
public function callEvent ( $eventName ) {
if ( $this->eventExists($eventName) ) {
if ( func_num_args() > 1 ) {
$args = func_get_args();
array_shift($args);
return call_user_func_array( $this->getEventListener($eventName), $args ) ;
} else return call_user_func( $this->getEventListener($eventName) );
}
}
public function __get ( $a ) {
$getter = "get" . $a;
if ( method_exists($this, $getter) ) return call_user_func( array(&$this,$getter) );
else throw new TException ( "__get", "proprietatea $a nu are getter");
}
public function __set ( $a, $v ) {
$setter = "set" . $a;
if ( strpos($a,"on") !== FALSE ) $this->addEventListener($a, $v);
elseif ( method_exists($this, $setter) ) return call_user_func( array(&$this,$setter), $v );
else throw new TException ( "__set", "proprietatea $a nu are setter");
}
public function __call ( $f, $a ) {
$eventResult = $this->callEvent("on".$f, $a);
$a[count($a)+1] = $eventResult;
return call_user_func_array( array( &$this,"_".$f ), $a ) ;
}
}
?>

    Blog din Moldova    FastCounter 

 
Copyright © 2008-2010 Foster1. All rights reserved.