Created
February 13, 2013 10:47
-
-
Save chriskoch/4943794 to your computer and use it in GitHub Desktop.
Using PHP 5.4 traits as getter and setter helper
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 | |
trait Getters | |
{ | |
/** | |
* calls Class::$name() | |
* | |
* @param string $name the name of a requested property | |
* @return mixed the result | |
*/ | |
public function __get($name) | |
{ | |
return $this->__call($name); | |
} | |
/** | |
* checks wether a get method get<$Name>() exists and calls it | |
* | |
* @param string $name | |
* @param array $args optional | |
* @return mixed | |
*/ | |
public function __call($name, $args = []) | |
{ | |
if (method_exists($this, $method = 'get' . ucfirst($name))) { | |
return $this->{$method}($args); | |
} else { | |
throw new \Exception('Method or property does not exists'); | |
} | |
} | |
} | |
trait Setters | |
{ | |
/** | |
* @param string $name property name | |
* @param mixed $value the value | |
*/ | |
public function __set($name, $value) | |
{ | |
if (method_exists($this, $method = 'set' . ucfirst($name))) { | |
$this->{$method}($value); | |
} else { | |
throw new \Exception('Private or protected properties are not accessible'); | |
} | |
} | |
} | |
class MyTest | |
{ | |
use Getters; | |
use Setters; | |
/** | |
* @var \DateTime | |
*/ | |
private $date; | |
/** | |
* @return \DateTime | |
*/ | |
public function getDate() | |
{ | |
return $this->date; | |
} | |
/** | |
* @param mixed $value | |
*/ | |
public function setDate($value) | |
{ | |
if ($value instanceof \DateTime) { | |
$this->date = $value; | |
} elseif (is_string($value)) { | |
$this->date = new \DateTime($value); | |
} elseif (is_int($value)) { | |
$this->date = new \DateTime(date(DATE_ATOM, $value)); | |
} | |
} | |
} | |
// Test it | |
$test = new MyTest(); | |
$test->date = strtotime('2012-12-31'); | |
var_dump($test); | |
$test->date = '2013-01-31'; | |
var_dump($test); | |
$test->date = new DateTime(); | |
var_dump($test->date); | |
var_dump($test->date()); | |
var_dump($test->getDate()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a gist for a blog post http://www.scandio.de/2013/02/getter-und-setter-mit-traits-php-5-4/