Tuesday, August 18, 2015

How to get value of protected object without getter/setter in php

Get value of protected object in php without getter/setter:

If there are any protected object and we want to get its value without creating any get() and set() method & without overriding, then use this method.

for e.g.
 I have a protected array:


Stripe\Coupon Object
(
    [_opts:protected] => Stripe\Util\RequestOptions Object
        (
            [headers] => Array
                (
                )
            [apiKey] => sk_test_Ghjgah2wFtSWkmvJXLge5siVGrM
        )
    [_values:protected] => Array
        (
            [id] => INSTA100
            [created] => 1439875363
            [percent_off] =>
            [amount_off] => 100
            [currency] => usd
            [object] => coupon
            [livemode] =>
            [duration] => once
            [redeem_by] =>
            [max_redemptions] =>
            [times_redeemed] => 0
            [duration_in_months] =>
            [valid] => 1
            [metadata] => Stripe\AttachedObject Object
                (
                    [_opts:protected] => Stripe\Util\RequestOptions Object
                        (
                            [headers] => Array
                                (
                                )
                            [apiKey] => sk_test_Gah2wFtSWkmvJXLge5siVGrM
                        )
                    [_values:protected] => Array
                        (
                        )
                    [_unsavedValues:protected] => Stripe\Util\Set Object
                        (
                            [_elts:Stripe\Util\Set:private] => Array
                                (
                                )
                        )
                    [_transientValues:protected] => Stripe\Util\Set Object
                        (
                            [_elts:Stripe\Util\Set:private] => Array
                                (
                                )
                        )
                    [_retrieveOptions:protected] => Array
                        (
                        )
                )
        )
)





Now i want to get all values of _values


For this i will use ReflectionClass which is a php class
               
$reflector = new \ReflectionClass($cpn);
                $classProperty = $reflector->getProperty('_values');
                $classProperty->setAccessible(true);
                $data = $classProperty->getValue($cpn);


Here $cpn is my object

Now print $data and you will get your required array.

Thanks

No comments:

Post a Comment