PHP

Get/Set Only Some Properties of a Class

WARNING: This is a slow function (listProperties()) and even slower with PHP’s loop mechanics. Do not use this in a loop. Store the results outside the loop and then use it in the loop:

class Test
{
    public function populate($user = Array())
    {
        $props = $this->listProperties();

        foreach ($user as $k => $v) {
            if (array_key_exists($k, $props)) {
                $this->{$k} = $v;
            }
        }
    }

    protected function listProperties()
    {
        $reflect = new ReflectionClass(get_class($this));
        $arr = [];
        foreach (
            $reflect->getProperties(
                ReflectionProperty::IS_PUBLIC + ReflectionProperty::IS_PROTECTED
            ) as $prop
        ) {
            $arr[$prop->getName()] = $this->{$prop->getName()};
        }
        return $arr;
    }
}

$var = new Test();
$var->populate(['d' => 1]);
var_dump($var);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s