26/03
2016
Magic getters and setters for your classes
Getters and setters for any class, with onSet listeners, (*1)
Magic can be installed using composer. Run this command:, (*2)
composer require hrn4n/magic
To use it simply create a class that extends the Access\Magic class:, (*3)
<?php class Person extends Access\Magic { protected $name; }
And that's it, you can start using getters and setters:, (*4)
<?php $me = new Person; $me->setName("Hernan"); $me->get("name"); # returns "Hernan" $me->getName(); # also returns "Hernan"
When you call $me->hasProperty()
it will return true if: the property exists and it's not empty, otherwise it will return false, (*5)
$me->isProperty()
Is a shorthand for: $me->getIsProperty()
OR $me->getProperty()
It will check first is 'isProperty' exists, if it doesn't then it checks if 'Property' exists, (*6)
Say we add a onNameSet to our Person class:, (*7)
<?php class Person extends Access\Magic { protected $name; public function onNameSet($name) { # convert name to uppercase before setting return strtoupper($name); } }
Then we run the following code:, (*8)
<?php $me = new Person; $me->set("name", "hernan"); # alternative way of setting properties $me->getName(); # returns "HERNAN"