Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP getter/setter to array

Tags:

oop

php

Following "problem"

PHP Class with a lot of propertys. A lot of Getters / Setter.

Is there any nice solution to convert all propertys to an array?

protected $name;
protected $date;

public function getName();
public function getDate();
public function asArray(); // call all getters?
like image 936
opHASnoNAME Avatar asked Dec 02 '22 05:12

opHASnoNAME


1 Answers

Is your API already defined and are you stuck with getX and setX methods? I much prefer properties. Less typing, better distinction between properties and methods, and resulting code looks more like PHP and less like Java. But exposing properties doesn't mean you lose encapsulation and make all your internals public. With __get and __set magic methods you can have pretty fine-grained control over what you present. Plus, it would be rather trivial to dump the properties as an array:

class Foo
{
    protected $properties;

    public function __construct() {
        $this->properties = array();
    }

    public function __set($prop, $value) {
        $this->properties[$prop] = $value;
    }

    public function __get($prop) {
        return $this->properties[$prop];
    }

    public function toArray() {
        return $this->properties;
    }
}

Alas, if you're stuck with setters/getters because of a cranky boss or some misunderstanding of what OOP must be, why not just cast the object to an array?

class Bar
{
    public $x;
    public $y;
    public $z;
    protected $a;
    protected $b;
    protected $c;
    private $q;
    private $r;
    private $s;

    public function __construct() {
    }

    public function setA($value) {
        $this->a = $value;
    }

    public function getA() {
        return $this->a;
    }

    public function setB($value) {
        $this->b = $value;
    }

    public function getB() {
        return $this->b;
    }

    public function setC($value) {
        $this->c = $value;
    }

    public function getC() {
        return $this->c;
    }

    public function toArray() {
        return (array)$this;
    }
}

Notice how public, protected, and private properties are cast:

$bar = new Bar();
print_r($bar->toArray());

array(9) {
  ["x"]=>
  NULL
  ["y"]=>
  NULL
  ["z"]=>
  NULL
  [" * a"]=>
  NULL
  [" * b"]=>
  NULL
  [" * c"]=>
  NULL
  [" Foo q"]=>
  NULL
  [" Foo r"]=>
  NULL
  [" Foo s"]=>
  NULL
}

Note that the array keys for protected/private don't start with a space, it's a null. You can re-key them, or even filter out protected/private properties if you like:

public function toArray() {
    $props = array();
    foreach ((array)$this as $key => $value) {
        if ($key[0] != "\0") {
            $props[$key] = $value;
        }
    }
    return $props;
}

You're working with a dynamic language; take advantage of that and enjoy it!

like image 143
Timothy Avatar answered Dec 04 '22 12:12

Timothy