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

前端 未结 8 1289
無奈伤痛
無奈伤痛 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:17

    The way I do it is the following:

    class test {
        protected $x='';
        protected $y='';
    
        function set_y ($y) {
            print "specific function set_y\n";
            $this->y = $y;
        }
    
        function __call($function , $args) {
            print "generic function $function\n";
            list ($name , $var ) = split ('_' , $function );
            if ($name == 'get' && isset($this->$var)) {
                return $this->$var;
            }
            if ($name == 'set' && isset($this->$var)) {
                $this->$var= $args[0];
                return;
            }
            trigger_error ("Fatal error: Call to undefined method test::$function()");
        }
    }
    
    $p = new test();
    $p->set_x(20);
    $p->set_y(30);
    print $p->get_x();
    print $p->get_y();
    
    $p->set_z(40);
    

    Which will output (line breaks added for clarity)

    generic function set_x
    specific function set_y
    
    generic function get_x
    20
    generic function get_y
    30
    
    generic function set_z
    Notice: Fatal error: Call to undefined method set_z() in [...] on line 16
    

提交回复
热议问题