Last active
January 11, 2018 10:22
-
-
Save imliam/ba8455dba30be201e474bae737f9ae16 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* Allows a method in a class to be called either statically or instanced. | |
* | |
* To use, ensure custom method names are camelCase starting withthe word | |
* "either". For example, a method defined as "eitherGetResults()" | |
* can be called in either of the two following ways: | |
* | |
* $exampleObject->getResults() | |
* ExampleClass::getResults() | |
*/ | |
trait EitherMethods | |
{ | |
public static function __callStatic($methodName, $arguments) | |
{ | |
$currentClass = get_called_class(); | |
$currentObject = new $currentClass; | |
$newMethodName = 'either' . ucfirst($methodName); | |
if (! method_exists($currentObject, $newMethodName)) { | |
throw new BadMethodCallException('Call to undefined method ' . get_class($currentObject) . '::' . $methodName . '()'); | |
} | |
return call_user_func_array([$currentObject, $newMethodName], $arguments); | |
} | |
public function __call($methodName, $arguments) | |
{ | |
$newMethodName = 'either' . ucfirst($methodName); | |
if (!method_exists($this, $newMethodName)) { | |
throw new BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $methodName . '()'); | |
} | |
return $this->{$newMethodName}(...$arguments); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: