0

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

2 Answers 2

2

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.