Skip to content

Instantly share code, notes, and snippets.

@aindong
Created April 16, 2015 15:47
Show Gist options
  • Save aindong/c66b92ff8f6d6232b1df to your computer and use it in GitHub Desktop.
Save aindong/c66b92ff8f6d6232b1df to your computer and use it in GitHub Desktop.
Dynamic setter/getter using __call magic method of php
<?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();
@sadortun
Copy link

sadortun commented Apr 7, 2017

There is a small error in the above code. Line 17-21, need to be moved after line 26

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment