PHP: Create “structures” in PHP 5.3

PHP: Crear “estructuras” en PHP 5.3

Jul 19 2009

Sometimes I had interest into creating a class that would contain simply a few attributes and no much more, and I ended doing something like this construction: ```php class mystruct { public $a, $b, $c; function __construct($a, $b, $c) { $this->a = $a; $this->b = $b; $this->c = $c; } } ``` ```php class struct { static public function create() { $obj = new static; $keys = array_keys((array)$obj); foreach (func_get_args() as $k => $v) $obj->{$keys[$k]} = $v; return $obj; } } ``` In previous PHP version, we can use t he constructor: ```php class struct { static function __construct() { $keys = array_keys((array)$obj); foreach (func_get_args() as $k => $v) $this->{$keys[$k]} = $v; return $this; } } ``` So we could have something like this: ```php class mystruct extends struct { public $a, $b, $c; } // PHP 5.3 mystruct::create(1, 2, 3); // Versiones anteriores new mystruct(1, 2, 3); ```
En alguna ocasión me ha interesado crear una clase que contendría simplemente unos cuantos atributos y poco más y al final he acabado haciendo un constructor del tipo: ```php class mystruct { public $a, $b, $c; function __construct($a, $b, $c) { $this->a = $a; $this->b = $b; $this->c = $c; } } ``` ```php class struct { static public function create() { $obj = new static; $keys = array_keys((array)$obj); foreach (func_get_args() as $k => $v) $obj->{$keys[$k]} = $v; return $obj; } } ``` Para versiones anteriores de php podemos usar el constructor: ```php class struct { static function __construct() { $keys = array_keys((array)$obj); foreach (func_get_args() as $k => $v) $this->{$keys[$k]} = $v; return $this; } } ``` Con lo que podríamos hacer lo siguiente: ```php class mystruct extends struct { public $a, $b, $c; } // PHP 5.3 mystruct::create(1, 2, 3); // Versiones anteriores new mystruct(1, 2, 3); ```