Skip to content

Instantly share code, notes, and snippets.

@jsebrech
Created September 28, 2013 08:45
Show Gist options
  • Save jsebrech/6740010 to your computer and use it in GitHub Desktop.
Save jsebrech/6740010 to your computer and use it in GitHub Desktop.
Demo of something like C# accessors in PHP using meta-programming
<?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