Created
September 30, 2020 04:56
-
-
Save devgnx/d42c54db033bf46da055bc30f9cdf161 to your computer and use it in GitHub Desktop.
Magic Getter and Setter trait
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 | |
namespace Domain\Shared; | |
trait MagicGetterSetter | |
{ | |
public function __set($name, $value) | |
{ | |
if (property_exists($this, $value)) { | |
$name = $this->toCamelCase($name); | |
$this->{$name} = $value; | |
} | |
} | |
public function __get($name) | |
{ | |
return $this->{$name}(); | |
} | |
/** | |
* Get/Set property | |
* | |
* @param string $name | |
* @param mixed $arguments | |
* @return $this|void | |
*/ | |
public function __call($name, $arguments) | |
{ | |
$is_getter = preg_match('/^get/', $name); | |
$is_setter = preg_match('/^set/', $name); | |
$property = lcfirst(preg_replace('/^(g|s)et/', '', $name)); | |
if (!$is_getter && !$is_setter) { | |
$is_getter = true; | |
} | |
if (property_exists($this, $property)) { | |
if ($is_getter) { | |
return $this->{$property}; | |
} else if (array_key_exists(0, $arguments)) { | |
$this->{$property} = $arguments[0]; | |
return $this; | |
} else { | |
throw new \BadMethodCallException("for " . __CLASS__ . "::{$name}()"); | |
} | |
} | |
throw new \BadMethodCallException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment