0

我有一个对象,假设它是这样的:

class Foo {
    var $b, $a, $r;

    function __construct($B, $A, $R) {
        $this->b = $B;
        $this->a = $A;
        $this->r = $R;
    }
}

$f = new Foo(1, 2, 3);

我想将该对象的属性的任意切片作为数组获取。

$desiredProperties = array('b', 'r');

$output = magicHere($foo, $desiredProperties);

print_r($output);

// array(
//   "b" => 1,
//   "r" => 3
// )
4

2 回答 2

2

假设属性是公开的,这应该可以工作:

$desiredProperties = array('b', 'r');
$output = props($foo, $desiredProperties);

function props($obj, $props) {
  $ret = array();
  foreach ($props as $prop) {
    $ret[$prop] = $obj->$prop;
  }
  return $ret;
}

注意: var在这个意义上可能已被弃用。这是PHP4。PHP5的方式是:

class Foo {
  public $b, $a, $r;

  function __construct($B, $A, $R) {
    $this->b = $B;
    $this->a = $A;
    $this->r = $R;
  }
}
于 2010-04-08T00:31:40.287 回答
2

...我在写问题的过程中想到了如何做到这一点...

function magicHere ($obj, $keys) {
    return array_intersect_key(get_object_vars($obj), array_flip($keys));
}
于 2010-04-08T00:32:26.900 回答