Skip to content

Instantly share code, notes, and snippets.

@ChrisBuchholz
Last active December 21, 2015 03:09
Show Gist options
  • Save ChrisBuchholz/6240407 to your computer and use it in GitHub Desktop.
Save ChrisBuchholz/6240407 to your computer and use it in GitHub Desktop.
<?php
class Synthesization {
private function signatureIsGetter($signature) {
if (preg_match('/^get/', $signature))
return true;
return false;
}
private function signatureIsSetter($signature) {
if (preg_match('/^set/', $signature))
return true;
return false;
}
private function getPropertyFromMethodSignature($signature) {
return lcfirst(preg_replace('/^(g|s)et/', '', $signature));
}
public function __call($method, $params) {
$property = $this->getPropertyFromMethodSignature($method);
if (property_exists($this, $property)) {
if ($this->signatureIsGetter($method))
return $this->{$property};
else if ($this->signatureIsSetter($method))
return $this->{$property} = $params[0];
}
return false;
}
}
<?php
class Synthesization {
private function signatureIsGetter($signature) {
return preg_match('/^get/', $signature) ? true : false;
}
private function signatureIsSetter($signature) {
return preg_match('/^set/', $signature) ? true : false;
}
private function getPropertyFromMethodSignature($signature) {
return lcfirst(preg_replace('/^(g|s)et/', '', $signature));
}
public function __call($method, $params) {
$property = $this->getPropertyFromMethodSignature($method);
$reflector = new ReflectionClass(get_class($this));
if ($reflector->hasProperty($property)) {
$prop = $reflector->getProperty($property);
$prop->setAccessible(true);
if ($this->signatureIsGetter($method))
return $prop->getValue($this);
else if ($this->signatureIsSetter($method))
return $prop->setValue($this, $params[0]);
$prop->setAccessible(false);
}
return false;
}
}
@ChrisBuchholz
Copy link
Author

Example use case:

class MyClass extends Synthesization {

    protected $a;

    public function __construct() {
        $this->setA('hest');
    }

}

$mc = new MyClass();

echo $mc->getA();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment