Is this a reasonable way to handle getters/setters in a PHP class?

前端 未结 8 1271
無奈伤痛
無奈伤痛 2020-12-16 03:50

I\'m going to try something with the format of this question and I\'m very open to suggestions about a better way to handle it.

I didn\'t want to just dump a bunch o

相关标签:
8条回答
  • 2020-12-16 04:24

    I've always handled this issue in a similar with a __call which ends up pretty much as boiler plate code in many of my classes. However, it's compact, and uses the reflection classes to only add getters / setters for properties you have already set (won't add new ones). Simply adding the getter / setter explicitly will add more complex functionality. It expects to be

    Code looks like this:

    /**
    * Handles default set and get calls
    */
    public function __call($method, $params) {
    
        //did you call get or set
        if ( preg_match( "|^[gs]et([A-Z][\w]+)|", $method, $matches ) ) {
    
            //which var?
            $var = strtolower($matches[1]);
    
            $r = new ReflectionClass($this);
            $properties = $r->getdefaultProperties();
    
            //if it exists
            if ( array_key_exists($var,$properties) ) {
                //set
                if ( 's' == $method[0] ) {
                    $this->$var = $params[0];
                }
                //get
                elseif ( 'g' == $method[0] ) {
                    return $this->$var;
                }
            }
        }
    }
    

    Adding this to a class where you have declared default properties like:

    class MyClass {
        public $myvar = null;
    }
    
    $test = new MyClass;
    $test->setMyvar = "arapaho";
    
    echo $test->getMyvar; //echos arapaho    
    

    The reflection class may add something of use to what you were proposing. Neat solution @Mark.

    0 讨论(0)
  • 2020-12-16 04:28

    I like having methods instead of just using public fields, as well, but my problem with PHP's default implementation (using __get() and __set()) or your custom implementation is that you aren't establishing getters and setters on a per-property basis. My problem with this is that adding "more logic later" requires that you add blanket logic that applies to all properties accessed with the getter/setter or that you use if or switch statements to evaluate which property you're accessing so that you can apply specific logic.

    I like your solution, and I applaud you for it--I'm just not satisfied with the limitations that PHP has when it comes to implicit accessor methods.

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