Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
// )
share|improve this question

2 Answers 2

...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));
}
share|improve this answer

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;
  }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.