Created
April 16, 2015 15:47
-
-
Save aindong/c66b92ff8f6d6232b1df to your computer and use it in GitHub Desktop.
Dynamic setter/getter using __call magic method of php
This file contains 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 | |
class Person | |
{ | |
protected $firstName; | |
protected $lastName; | |
/** | |
* Magic method call for setter and getter | |
* | |
* @param $methodName | |
* @param $params | |
* | |
* @return mixed | |
*/ | |
public function __call($methodName, $params = null) | |
{ | |
// Check if a property does exists | |
if (!property_exists($this, $attr)) { | |
exit('Opps! Property does not exists'); | |
} | |
// Get the method prefix to determine action | |
$methodPrefix = substr($methodName, 0, 3); | |
// Get the attribute to do action with | |
$attr = self::camelCase(substr($methodName, 3)); | |
// Check action (Set/Get) | |
if ($methodPrefix == 'set' && count($params) == 1) { | |
// Get the parameter value | |
$value = $params[0]; | |
// Set the value | |
$this->{$attr} = $value; | |
} elseif ($methodPrefix == 'get') { | |
// Return the value | |
return $this->{$attr}; | |
} else { | |
exit('Opps! The method is not defined!'); | |
} | |
} | |
/** | |
* Convert a string into a CamelCase string format | |
* | |
* @param $str | |
* @param $noStrip | |
* | |
* @return String | |
*/ | |
public static function camelCase($str, array $noStrip = array()) | |
{ | |
// non-alpha and non-numeric characters become spaces | |
$str = preg_replace('/[^a-z0-9' . implode("", $noStrip) . ']+/i', ' ', $str); | |
$str = trim($str); | |
// uppercase the first character of each word | |
$str = ucwords($str); | |
$str = str_replace(" ", "", $str); | |
$str = lcfirst($str); | |
return $str; | |
} | |
} | |
$person = new Person(); | |
$person->setFirstName('alleo'); | |
echo $person->getFirstName(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a small error in the above code. Line 17-21, need to be moved after line 26