views:

43

answers:

2

I have an object, let's say it's like this:

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);

I want to get an arbitrary slice of this object's properties as an array.

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

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

print_r($output);

// array(
//   "b" => 1,
//   "r" => 3
// )
+1  A: 

This should work assuming the properties are public:

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

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

Note: var in this sense is possibly deprecated. It's PHP4. The PHP5 way is:

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

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

...I thought of how to do this half way through writing the question...

function magicHere ($obj, $keys) {
    return array_intersect_key(get_object_vars($obj), array_flip($keys));
}
nickf