How to implement __isset() magic method in PHP?

后端 未结 3 426
名媛妹妹
名媛妹妹 2020-12-18 23:18

I\'m trying to make functions like empty() and isset() work with data returned by methods.

What I have so far:

abstract cla         


        
相关标签:
3条回答
  • 2020-12-18 23:36

    Your code returns error because of these lines:

    if(method_exists($this, $getter))
    return isset($this->$getter());
    

    You can just replace it with:

    if (!method_exists($this), $getter) {
        return false; // method does not exist, assume no property
    }
    $getter_result = $this->$getter();
    return isset($getter_result);
    

    and it will return false if the getter is not defined or it returns NULL. I propose you should better think of the way you determine some property is set or not.

    The above code is also assuming that you are creating getters for all of your properties, thus when there is no getter, the property is assumed as not set.

    Also, why are you using getters? They seem to be some overkill here.

    0 讨论(0)
  • 2020-12-19 00:00

    A bit more option not to depend on getter

    public function __isset($name)
    {
        $getter = 'get' . ucfirst($name);
        if (method_exists($this, $getter)) {
            return !is_null($this->$getter());
        } else {
            return isset($this->$name);
        }
    }
    
    0 讨论(0)
  • 2020-12-19 00:01
    public function __isset($name){
        $getter = 'get'.ucfirst($name);
        return method_exists($this, $getter) && !is_null($this->$getter());
    }
    

    This check whether or not $getter() exists (if it does not exist, it's assumed that the property also does not exist) and returns a non-null value. So NULL will cause it to return false, as you would expect after reading the php manual for isset().

    0 讨论(0)
提交回复
热议问题