Ver Mensaje Individual
  #4 (permalink)  
Antiguo 28/05/2014, 12:56
Avatar de Italico76
Italico76
 
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 17 años
Puntos: 292
Respuesta: Nuevos tipos de datos: Struct de C y Range

Cita:
Iniciado por pateketrueke Ver Mensaje
Suena interesante, me pregunto si la extensión SPL de PHP no implementa algo parecido.

Digo, PHP ha evolucionado mucho y no me sorprendería que exista algo similar, en caso de no existir veo elegante tu implementación.
Mucha gracias por las flores


VERSION ACTUALIZADA DE "STRUCT":

Código PHP:
Ver original
  1. <?php
  2. /*
  3.     Struct as in C
  4.     @author: Pablo Bozzolo
  5.  
  6.     struct database {
  7.         int id_number;
  8.         int age;
  9.         float salary;
  10.     };
  11. */
  12.  
  13. Class Struct
  14. {
  15.     protected $_field = array();
  16.     protected $_type  = array();
  17.     protected $_name = null;
  18.     protected $_type_hinting = true;   
  19.     protected $_tipos_ = array ("boolean","integer","double","string","array","object","resource","NULL" );
  20.     protected $_aliases = array(); 
  21.    
  22.     /* setter on-off */
  23.     public function alias($flag=true)
  24.     {
  25.         if ($flag)
  26.             $this->_aliases=array('bool'=>'boolean','int'=>'integer','float'=>'double','str'=>'string');
  27.         else
  28.             $this->_aliases=null;
  29.            
  30.         return $this;  
  31.     }
  32.        
  33.     public function __construct($name)
  34.     {
  35.         $this->_name=$name;
  36.         $this->alias();
  37.     }
  38.    
  39.     // sin implentar
  40.     public function __clone()
  41.     {   }
  42.  
  43.     public function typeHinting($flag)
  44.     {
  45.         $this->_type_hinting=$flag;        
  46.     }
  47.    
  48.     public function parse($str)
  49.     {
  50.         $patt = '|^[\s]{0,}([a-z_]*)[\s]{0,}([$]?[a-z_]*[0-9a-z]*)[\s]{0,}[=;]?[\s]{0,}(.*)|i';
  51.        
  52.         $statements = explode(';',trim($str));
  53.         foreach ($statements as $st)
  54.         {      
  55.             if (strlen($st)==0)
  56.                 continue;
  57.                
  58.             if (preg_match($patt,$st,$resul))
  59.             {
  60.                 $type = $resul[1];
  61.                 $var_name = str_replace('$','',$resul[2]);
  62.                 $default = $resul[3];              
  63.                                
  64.                 if ( (empty($var_name)) and (!empty($type)) )
  65.                 {
  66.                     $var_name=$type;
  67.                     $type=null;
  68.                 }
  69.                
  70.                 $this->create($var_name,$type,$default);                               
  71.             }else
  72.                 echo "FAIL PARSING : $st \n";;
  73.         }
  74.         return $this;
  75.     }
  76.  
  77.     public function create($var,$type=null,$val=null)
  78.     {
  79.         if ((!empty($type)) and ($type!="unknown type"))
  80.         {      
  81.             // alias
  82.             foreach ((array) $this->_aliases as $alias => $typo)
  83.                 if ($type==$alias) $type=$typo;
  84.                        
  85.             if ((in_array($type,$this->_tipos_)))
  86.                 $this->_type[$var] = $type;
  87.             else
  88.                 throw new Exception ("Tipo de dato no soportado");     
  89.         }              
  90.                
  91.    
  92.         $this->_field[$var] = $val;    
  93.         return $this;
  94.     }
  95.    
  96.    
  97.     public function __set($var,$val)
  98.     {      
  99.         if (!empty($this->_type[$var]))
  100.             if (gettype($val)!= $this->_type[$var])
  101.                 throw new Exception ("Tipos no coinciden");    
  102.    
  103.         if (in_array($var,array_keys($this->_field)))
  104.             $this->_field[$var] = $val;    
  105.         else
  106.             throw new Exception("No existe el campo $var!");
  107.     }
  108.    
  109.     public function __get($var)
  110.     {
  111.         return $this->_field[$var];            
  112.     }
  113. }


A considerar si se usa parse()

Cita:
1.- Las propiedades del struct pueden o no comenzar con $ como las variables (opcional)

2.- No se admiten ningun tipo de comentario inline ni multiline (no molesten xD)
--
Aca un tema viejito donde me surgio la idea de la clase Range
__________________
Salu2!

Última edición por Italico76; 29/05/2014 a las 06:37