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

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

    @Brian

    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.

    That's not quite true. Take my first example:

    class PropTest extends PropertyHandler
    {
        public function __construct()
        {
            parent::__construct();
        }
    }
    
    $props = new PropTest();
    
    $props->setFirstName("Mark");
    echo $props->getFirstName();
    

    Let's say that I need to add some logic for validating FirstNames. All I have to do is add a setFirstName method to my subclass and that method is automatically used instead.

    class PropTest extends PropertyHandler
    {
        public function __construct()
        {
            parent::__construct();
        }
    
        public function setFirstName($name)
        {
            if($name == 'Mark')
            {
                echo "I love you, Mark!";
            }
        }
    }
    

    I'm just not satisfied with the limitations that PHP has when it comes to implicit accessor methods.

    I agree completely. I like the Python way of handling this (my implementation is just a clumsy rip-off of it).

提交回复
热议问题