简体   繁体   English

PHP getter / setter to array

[英]PHP getter/setter to array

Following "problem" 关注“问题”

PHP Class with a lot of propertys. PHP类具有很多属性。 A lot of Getters / Setter. 很多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?

Is your API already defined and are you stuck with getX and setX methods? 您的API是否已经定义,是否仍然存在getX和setX方法? I much prefer properties. 我更喜欢物业。 Less typing, better distinction between properties and methods, and resulting code looks more like PHP and less like Java. 减少输入,更好地区分属性和方法,结果代码看起来更像PHP,而不像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. 使用__get和__set魔术方法,您可以对所呈现的内容进行非常精细的控制。 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? 唉,如果你因为胡思乱想的老板或者对OOP 必须有什么误解而坚持使用setter / getter,为什么不把对象强制转换为数组呢?

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: 请注意如何转换public,protected和private属性:

$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. 请注意,protected / private的数组键不以空格开头,它是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! 利用它,享受它!

How about using ReflectionClass and ReflectionMethod, something like this: 如何使用ReflectionClass和ReflectionMethod,如下所示:

class PropertyHolder
{
    private $name;
    private $date;
    private $anotherProperty;

    public function __construct($name, $date)
    {
        $this->name = $name;
        $this->date = $date;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getDate()
    {
        return $this->date;
    }

    public function asArray()
    {
        $result = array();

        $clazz = new ReflectionClass(__CLASS__);
        foreach ($clazz->getMethods() as $method) {
            if (substr($method->name, 0, 3) == 'get') {
                $propName = strtolower(substr($method->name, 3, 1)) . substr($method->name, 4);

                $result[$propName] = $method->invoke($this);
            }
        }

        return $result;
    }

You could use PHP's reflection capabilities. 您可以使用PHP的反射功能。 Here's an example: 这是一个例子:

Try looking into get_object_vars() , get_class_vars and others in the same category. 尝试查看同一类别中的get_object_vars()get_class_vars和其他人。 The examples shown there look like pretty much what you need. 这里显示的例子几乎就像你需要的那样。 Check the comments there (for example http://www.php.net/manual/en/function.get-class-vars.php#87772 ) they already provide ways that suit your needs. 检查那里的评论(例如http://www.php.net/manual/en/function.get-class-vars.php#87772 )他们已经提供了适合您需求的方法。

A simple (array) cast on $this will suffice: $this上的简单(array)强制转换就足够了:

(array) $this;

If you have additional properties (private ones for example, that shall not be toArray()ed) you can afterwards unset these: 如果您有其他属性(例如私有属性,不应该是toArray()ed),您可以在以后取消设置:

public function toArray() {
    $array = (array) $this;
    unset($array['private'], $array['privateagain']);
    return $array;
}

One option would be to create an array in your constructor. 一种选择是在构造函数中创建一个数组。 You will have one getter and one setter.. When you want to set or get something, do something like: 你将有一个吸气剂和一个二传手。当你想要设置或获得某些东西时,做一些类似的事情:

$foo->get( 'UID' ); //(to get user id)
or
$foo->set( 'UID', 5 ); // to set something)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM