문제

My situation is quite simple, but i'm still looking for a nice and short solution for it. Here is my case:

I receive a soap response object which is my be different from a call to another. Sometimes, these properties are objects themselves and may have properties we have to get. For this, an array is set for each type of call to select the data wanted and discard the rest.

By example, in a call we receive an object like this: (I made a code easy to test by mocking the received object)

$objTest = new stdClass();
$objTest->Content1 = "";
$objTest->Content2 = new stdClass();
$objTest->Content2->prop1=1;
$objTest->Content2->prop2=2;
$objTest->Content2->prop3=3;
$objTest->Content3 = 3;
$objTest->Content4 = array('itm1'=>1, 'itm2'=>'two');

i want to check if $objTest->Content2->prop3 exist, but i don't know at the right moment i am looking for this because what i'm looking for is in the associative array.

The array for the call look like:

$map = array('Content3','Content2->prop3');

From now i am able to get the content of the Content3 property by doing this:

foreach ($map as $name => $value) {
    if (isset($object->$name)) {
        echo "$value: ". json_encode($object->$name)."\n";
    }
}

But not for the other because of the reference "->".

Now my question: Is there a way to get an unknown property of an unknown object as displayed above?

This is a result of the previous test:

Dump of objTests:

object(stdClass)[1]

public 'Content1' => string '' (length=0)

public 'Content2' => object(stdClass)[2]

    public 'prop1' => int 1

    public 'prop2' => int 2

    public 'prop3' => int 3

public 'Content3' => int 3

public 'Content4' => array (size=2)

    'itm1' => int 1

    'itm2' => string 'two' (length=3)

Trying to access the proprerty prop3 of the content2 of the object with a string:

Standard way to get the value : $objTest->Content2->prop3

Result : 3

Test string: "Content3"

Result: 3

Test astring: "Content2->prop3"

( ! ) Notice: Undefined property: stdClass::$Content2->prop3

Hope i put everything to help understand my situation!

Thanks!

도움이 되었습니까?

해결책

I don't know of a built-in PHP function that does this, but a function could be used to break up the string of properties and iterate through them to find the value of the last one in the string.

function get_property($object, $prop_string, $delimiter = '->') {
    $prop_array = explode($delimiter, $prop_string);
    foreach ($prop_array as $property) {
        if (isset($object->{$property}))
            $object = $object->{$property};
        else
            return;
    }
    return $object;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top