Last active
December 11, 2015 15:39
-
-
Save pjdietz/4622383 to your computer and use it in GitHub Desktop.
Simple implementation of magic accessor methods (__get, __set, __isset, __unset) for PHP classes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Use these methods to create automatic properties. When a property would be accessed, | |
* PHP will look for a function prefixed with get, set, isset, or unset followed by | |
* the property name with the first name capitalized. For example, the $this->name | |
* would be accessed as getName(), setName(), issetName(), and unsetName(). | |
*/ | |
/** | |
* @param string $propertyName | |
* @return mixed | |
*/ | |
public function __get($propertyName) | |
{ | |
$method = 'get' . ucfirst($propertyName); | |
if (method_exists($this, $method)) { | |
return $this->{$method}(); | |
} | |
} | |
/** | |
* @param string $propertyName | |
* @param $value | |
*/ | |
public function __set($propertyName, $value) | |
{ | |
$method = 'set' . ucfirst($propertyName); | |
if (method_exists($this, $method)) { | |
$this->{$method}($value); | |
} | |
} | |
/** | |
* @param string $propertyName | |
* @return mixed | |
*/ | |
public function __isset($propertyName) | |
{ | |
$method = 'isset' . ucfirst($propertyName); | |
if (method_exists($this, $method)) { | |
return $this->{$method}(); | |
} | |
} | |
/** | |
* @param string $propertyName | |
*/ | |
public function __unset($propertyName) | |
{ | |
$method = 'unset' . ucfirst($propertyName); | |
if (method_exists($this, $method)) { | |
$this->{$method}(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment