Created
September 28, 2013 08:45
-
-
Save jsebrech/6740010 to your computer and use it in GitHub Desktop.
Demo of something like C# accessors in PHP using meta-programming
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 | |
// requires PHP 5.4 | |
trait ClassAccessors { | |
public function __set($name, $value) { | |
$methodName = "set".ucfirst($name); | |
if (method_exists($this, $methodName)) { | |
$this->$methodName($value); | |
} else { | |
$this->$name = $value; | |
} | |
} | |
public function __get($name) { | |
$methodName = "get".ucfirst($name); | |
if (method_exists($this, $methodName)) { | |
return $this->$methodName(); | |
} else { | |
return $this->$name; | |
} | |
} | |
} | |
class Demo | |
{ | |
use ClassAccessors; | |
private $Name = ""; | |
public function setName($value) { | |
$this->Name = $value; | |
} | |
public function getName() { | |
return empty($this->Name) ? "NA" : $this->Name; | |
} | |
} | |
header("Content-Type: text/plain"); | |
$demo = new Demo(); | |
$demo->Name = "test"; | |
echo $demo->Name . PHP_EOL; | |
$demo->Name = ""; | |
echo $demo->Name; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment