Very nice mbzuchalski. But it seems to work only with public variables. Just change your switch to this so that it can access private / secure:
switch($match[1]) { case 'get': return self::${$property->name}; case 'set': return self::${$property->name} = $args[0]; }
And you probably want to modify the if to limit the available variables, otherwise it will result in them being closed or protected.
if ($reflector->hasProperty($property) && in_array($property, array("allowedBVariable1", "allowedVariable2"))) {...)
So, for example, I have a class designed to output various data for me from a remote server using the ssh pear module, and I want it to make certain assumptions about the target directory based on which server it was asked to look at. A thin version of the mbrzuchalski method is ideal for this.
static public function __callStatic($method, $args) { if (preg_match('/^([gs]et)([AZ])(.*)$/', $method, $match)) { $reflector = new \ReflectionClass(__CLASS__); $property = strtolower($match[2]). $match[3]; if ($reflector->hasProperty($property)) { if ($property == "server") { $property = $reflector->getProperty($property); switch($match[1]) { case 'set': self::${$property->name} = $args[0]; if ($args[0] == "server1") self::$targetDir = "/mnt/source/"; elseif($args[0] == "server2") self::$targetDir = "/source/"; else self::$targetDir = "/"; case 'get': return self::${$property->name}; } } else throw new InvalidArgumentException("Property {$property} is not publicly accessible."); } else throw new InvalidArgumentException("Property {$property} doesn't exist."); } }
Claymore Mar 11 '14 at 2:26 a.m. 2014-03-11 14:26
source share