Abstract properties in PHP

Leave a Reply

Comment as a guest.

  1. This seems like a scenario where PHP’s Java-like properties become apparent.

    And correct me if I’m wrong: the difference between this method and a getter is a nuanced difference? e.g., this is a way where you can interact directly with the $_abstract_properties without using a defined getter ($foo = $this->_abstract_properties['array']['rules'] instead of $foo = Validator()->getProperty( 'array', 'rules' ))?

    1. This seems like a scenario where PHP’s Java-like properties become apparent.

      Yeah, PHP has had quite an influence from Java in last few years, not that its bad. Java has some cool stuff & like Igor Wiedler said in his talk at TakeOff 2013 – PHP is like a pirate, it takes the good stuff from everywhere! 😉

      And correct me if I’m wrong: the difference between this method and a getter is a nuanced difference?

      What I’ve shown here is not a getter, its an implementation of abstract properties. Like if you declare an abstract method then all child classes have to define that method, its not optional. Similarly what if you need all child classes to have certain properties defined? Since natively there’s no concept of abstract properties, this implementation would allow you to declare the property names with types and any child class of Validator here would need to define those properties with their respective types else PHP will throw a LogicException. I’ve updated the post above with an example of how abstract properties can be of use (Validator::validate()) and an example of child class with its usage. I hope that would clear the confusion. 🙂

    2. where you can interact directly with the $_abstract_properties without using a defined getter ($foo = $this->_abstract_properties['array']['rules'] instead of $foo = Validator()->getProperty( 'array', 'rules' ))

      Actually, if you need to implement this (get a property of an object without explicitly calling a getter method) then you can always implement __get() in your class.

Sliding Sidebar