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 に答える