Last active
December 26, 2015 18:38
-
-
Save asp24/7195433 to your computer and use it in GitHub Desktop.
PHP Public Method name as Callable property idea.
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 | |
class PropertyExtenderRepo { | |
protected static $instance; | |
public static function getInstance() | |
{ | |
if (self::$instance === null) { | |
self::$instance = new self(); | |
} | |
return self::$instance; | |
} | |
protected $classMethods = array(); | |
final private function __construct() | |
{ | |
// | |
} | |
final private function __clone() | |
{ | |
// | |
} | |
public function getClassPublicMethodsNames($className) | |
{ | |
if (!array_key_exists($className, $this->classMethods)) { | |
$this->classMethods[$className] = array(); | |
// | |
$rClass = new ReflectionClass($className); | |
$rMethods = $rClass->getMethods(ReflectionMethod::IS_PUBLIC); | |
/** @var ReflectionMethod $rMethod */ | |
foreach ($rMethods as $rMethod) { | |
$this->classMethods[$className][] = $rMethod->getName(); | |
} | |
} | |
return $this->classMethods[$className]; | |
} | |
} | |
trait MethodPropertyBuilder { | |
protected function buildVars() | |
{ | |
$repo = PropertyExtenderRepo::getInstance(); | |
foreach ($repo->getClassPublicMethodsNames(__CLASS__) as $methodName) { | |
if (property_exists($this, $methodName)) { | |
throw new LogicException(sprintf('Class "%s" already has property "%s"', __CLASS__, $methodName)); | |
} | |
$this->{$methodName} = array($this, $methodName); | |
} | |
} | |
} | |
/** | |
* Class fooClass | |
* | |
* @property Callable $b Method b callable property | |
* @property Callable $c Method c callable property | |
*/ | |
class fooClass { | |
use MethodPropertyBuilder; | |
public function __construct() | |
{ | |
$this->buildVars(); | |
} | |
function b() | |
{ | |
return 1; | |
} | |
public function c() { | |
return 2; | |
} | |
} | |
$fooClass = new fooClass(); | |
assert(call_user_func($fooClass->b) === $fooClass->b()); | |
assert(call_user_func($fooClass->c) === $fooClass->c()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment