Reflection in PHP

Sometimes, it’s useful to set properties within a PHP class, but also return those same properties if perhaps, they’re public so can be accessed directly without exposing the rest of the class. The most accurate way of doing this IMO, is by using Reflection via PHP’s ReflectionClass.

Here’s a simple concept:

<?php
namespace Application\Model;
class MyModelClass
{
    protected $aProtectedProperty; 
    private $aPrivateProperty; 
    public $aPublicProperty;
    public $anotherPublicProperty;

    public function __construct(\An\Object $foo)
    {
        $this->aProtectedProperty = $foo;
    }

    public function setPrivateProperty(\Bar $baz)
    {
        $this->aPrivateProperty = $baz;
    }

    public function doStuffs()
    {
        $this->aPublicProperty = $this->aProtectedProperty->getThings();
        $this->anotherPublicProperty = $this->aProtectedProperty->getSomethingSpecific($this->aPrivateProperty);

        return $this->getPublicData();
    }

    protected function getPublicData()
    {
        // Setup reflection
        $reflect = new \ReflectionClass($this);

        // Get only public properties $properties = $reflect->getProperties( \ReflectionProperty::IS_PUBLIC );

        // Return public properties as simple stdClass
        $data = new \stdClass();

        foreach ($properties as $prop) {
            $propName = $prop->getName();
            $data->$propName = $prop->getValue($this);
        }

        return $data;
    }
}

This leaves the original data stored in the public properties for potential use with other methods, but also provides a simple way of accessing the public data without having to return the entire class.

We can also add, edit or remove the public properties to allow more, or less data returned.