2017-09-18 7 views
1

パスを持つプロパティ(...)のプロパティのプロパティを取得/設定したいと考えています。例えば、私はどのように再帰なしでパスを持つプロパティを動的に取得/設定できますか?

$obj->a->b->c 

を持っている場合、私は、私はそれを得るために、この関数を書いて、それは、配列やオブジェクトの値のために動作しますが、私は、オブジェクトのためにそれを必要とする

get_property(["a", "b", "c"], $obj) 

でそれを取得したいと思い。

public static function get_value_by_path($index, $array) { 

    if (!$index || empty($index)) 
     return NULL; 

    if (is_array($index)) { 
     if (count($index) > 1) { 
      if (is_array($array) && array_key_exists($index[0], $array)) { 
       return static::get_value_by_path(array_slice($index, 1), $array[$index[0]]); 
      } 
      if (is_object($array)) { 
       return static::get_value_by_path(array_slice($index, 1), $array->{$index[0]}); 
      } 
      return NULL; 
     } 
     $index = $index[0]; 
    } 

    if (is_array($array) && array_key_exists($index, $array)) 
     return $array[$index]; 

    if (is_object($array) && property_exists($array, $index)) return $array->$index; 
     return NULL; 
} 

私の質問は:それは再帰なしでこれを行うことが可能ですか?

類似の質問はありませんでした。

+0

もしあなたが配列のためにそれを行うことができれば、オブジェクトのために問題を起こすのはどこですか? – CBroe

+0

何もありません。私はすでにそれをやった。私の質問は:私は再帰なしでそれを行うことができますか? – TheDeveloper

+0

質問を一致させることはできますか?設定プロパティについて質問し、プロパティを取得するメソッドのコードを表示します。あなたは1つを選べますか?私は、あなたが表示するコードの代わりをしたいと思う。そうですか? –

答えて

1

以下この関数は、それを行います。

function get_property($propertyPath, $object) 
{ 
    foreach ($propertyPath as $propertyName) { 
    // basic protection against bad path 
    if (!property_exists($object,$property)) return NULL; 
    // get the property 
    $property = $object->{$propertyName}; 
    // if it is not an object it has to be the end point 
    if (!is_object($property)) return $property; 
    // if it is an object replace current object 
    $object = $property; 
    } 
    return $object; 
} 

あなたは正確にいくつかのエラーコードで構築することができますしたいのかによって異なります。あなたはこのような何かを設定したい場合は、get関数を使用することができます。

function set_property($propertyPath, &$object, $value) 
{ 
    // pop off the last property 
    $lastProperty = array_pop($propertyPath); 
    // get the object to which the last property should belong 
    $targetObject = get_property($propertyPath,$object); 
    // and set it to value if it is valid 
    if (is_object($targetObject) && property_exists($targetObject,$lastProperty)) { 
    $targetObject->{$lastProperty} = $value; 
    } 
} 

私はしかし、再帰好きですが、それでこれらの機能は、おそらくより良いかもしれません。

+0

@TheDeveloper:はい、申し訳ありませんが、慎重にコードをチェックしませんでした。アンパサンドのため 'set_property()'の '$ object'を変更しました。 –

+0

さらに簡素化しました。 –

関連する問題