Quick actions

cmd+k|ctrl+k

Navigation

Languages

ReflectionObjectTest

Snippet info

Language

Php

Visibility

public

Author

prodreg

Created

2016-08-03T13:39:07Z

Updated

2016-08-03T13:58:49Z

<?php

class ClassWithPrivateAttribute {
    public $myPublicAttribute = "I'm public\n";
    private $myPrivateAttribute = "I'm private\n";
}

$objectToInspect = new ClassWithPrivateAttribute();

echo "Output public attribute: " . $objectToInspect->myPublicAttribute;

// not possible
//echo "Output private attribute: " . $objectToInspect->myPrivateAttribute;

// use reflection instead
// get reflection object
$reflectionObject = new ReflectionObject($objectToInspect);

// get reference on the property
$prop = $reflectionObject->getProperty('myPrivateAttribute');

// set property to accessible
$prop->setAccessible(true);

// get the value
echo "Output private attribute: " . $prop->getValue($objectToInspect);
INFO