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
PHP

How to get the child (or child-child) class name inside of a parent

Partially taken from this Stack Overflow question.

You have three classes:- MongoDB.php which is the parent of Model.php which is the parent of Session.php. What would be an easy way of getting Session (class name) in MongoDB?

function getCollectionClass(){
    return get_class($this);
}

get_class() means get the instance name of the procedure class whilst get_class($this) means get the instance name of the class in $this context and since $this is actually the Session.php class it will return Session.