PHP:从对象

时间:2018-04-07 07:10:15

标签: php functional-programming php-7

我有一个像这样的简单类:

class MyClass {

    public $color = 'red';
    public $width = 200;
    public $height = 100;

    public function getValues(array $properties) {
        return array_map(function($property) {
            return $this->$property;
        }, $properties);
    }

}

我想做以下事情:

$values = (new MyClass)->getValues(['width', 'height']);

$values最终会包含此数组:[200, 100]

以上示例完全正常,所以我的问题是: 我们如何简化getValues()方法?当然有一种更简单的方法可以实现这一目标吗?

要求:

  • 它应该是功能性的(对于/ while循环没有)。 < - 我的例子中符合此标准
  • 不应使用回调函数。 < - 此标准在我的示例
  • 不符合

2 个答案:

答案 0 :(得分:2)

您可以将类变量存储在数组中,然后使用array_intersect_key()array_flip()来实现该目标。这是一个例子。

class MyClass {

    public $values = [
        'color'  => 'red',
        'width'  => '200',
        'heigth' => '100'
    ];

    public function getValues (array $properties) {
        return array_intersect_key ($this -> values, array_flip ($properties));
    }

    //EDIT 2

    public function set_value ($key, $value) {
        $this -> values[$key] = $value;
    } 

}

//编辑(感谢mae

还可以使用ReflectionClass()getProperties()生成类属性的数组。

//编辑(感谢Nigel Ren

可以使用get_object_vars()来实现相同的输出,而不是反射。

class MyClass {

    public $color  = 'red';
    public $width  = '200';
    public $heigth = '100';

    public function getValues (array $properties) {
        return array_intersect_key (get_object_vars ($this), array_flip ($properties));
    }

}

答案 1 :(得分:-1)

考虑一种新方法:

class MyClass
{
    public $prop = array();

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

    public function get($key)
    {
        return $this->prop[$key];
    }
}

$o = new MyClass();

$o->set('color', 'blue');
$o->set('pi', 3.14);

$o->get('color'); // blue
$o->get('pi'); // 3.14