使用php Reflection API制作动态getter和setter

时间:2018-05-06 12:03:31

标签: php reflection

我有一些有很多属性的类!

我没有在类中创建很多getter和setter,而是决定创建一个抽象类作为模板,我有一个魔术函数__call来设置和使用Php Reflection API获取属性值,如下所示:< / p>

public function __call($name, $args)
{
    //Check to see if we are getting a property value.
    if (preg_match("/get/i", $name)) {
        //Normalize method name, in case of camel case.
        $name = strtolower($name);

        //Find the start of get/set in the method.
        $pos = strpos($name, "get") + strlen("get");

        //Strip get / set from method. Get only property name.
        $name = substr($name, $pos, strlen($name) - $pos);

        //Refelct child class object.
        $reflection = new \ReflectionClass($this);

        //Get child class properties.
        $props = $reflection->getProperties();

        //Loop through the init. class properties.
        foreach ($props as $prop) {
            //Check if the property its array so we can search the keys in an array.
            if (is_array($this->{$prop->getName()})) {
                //So it's an array, check if array property has the key that we are looking for.
                if (array_key_exists($name, $this->{$prop->getName()})) {
                    return $this->{$prop->getName()}[$name];
                }

            }
            //If its not array then check for the property name that we are looking for.
            else if ($prop->getName() == $name) {
                return $this->$name;
            }
        }
        return null;

    }
    //Same thing here same like in get method, but instead of getting the method
    //here we will be setting a property value.
    else if (preg_match("/set/i", $name)) {
        $name  = strtolower($name);
        $pos   = strpos($name, "set") + strlen("set");
        $name  = substr($name, $pos, strlen($name) - $pos);
        $value = "";

        //Make sure that we have an argument in there.
        if (count($args) >= 1) {
            $value = $args[0];
        }

        $reflection = new \ReflectionClass($this);
        $props      = $reflection->getProperties();

        foreach ($props as $prop) {
            if (is_array($this->{$prop->getName()})) {

                if (array_key_exists($name, $this->{$prop->getName()})) {
                    $this->{$prop->getName()}[$name] = $value;
                }

            } else if ($prop->getName() == $name) {
                $this->$name = $value;
            }
        }
    }
}

我的问题是:

  

这是制作动态getter和setter的好方法吗?   这是与儿童类吸气者和比较的比较的缺点   制定者!什么是处理未找到属性的最佳方法   抛出异常或返回null?

0 个答案:

没有答案