PHP: Create “structures” in PHP 5.3

PHP: Crear “estructuras” en PHP 5.3

19 Jul 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:

class mystruct {  
    public $a, $b, $c;  
    function __construct($a, $b, $c) {  
        $this->a = $a;  
        $this->b = $b;  
        $this->c = $c;  
    }  
}  
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:

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:

class mystruct extends struct { public $a, $b, $c; }  
// PHP 5.3  
mystruct::create(1, 2, 3);  
// Versiones anteriores  
new mystruct(1, 2, 3);  

Spanish

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:

class mystruct {  
    public $a, $b, $c;  
    function __construct($a, $b, $c) {  
        $this->a = $a;  
        $this->b = $b;  
        $this->c = $c;  
    }  
}  
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:

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:

class mystruct extends struct { public $a, $b, $c; }  
// PHP 5.3  
mystruct::create(1, 2, 3);  
// Versiones anteriores  
new mystruct(1, 2, 3);