Skip to content

Instantly share code, notes, and snippets.

@imliam
Last active January 11, 2018 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imliam/ba8455dba30be201e474bae737f9ae16 to your computer and use it in GitHub Desktop.
Save imliam/ba8455dba30be201e474bae737f9ae16 to your computer and use it in GitHub Desktop.
<?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);
}
}
@imliam
Copy link
Author

imliam commented Jan 11, 2018

Example usage:

<?php

class ExampleClass
{
    use EitherMethods;

    private $list = [];

    public function eitherA()
    {
        array_push($this->list, 'a');
        return $this;
    }

    public function eitherB()
    {
        array_push($this->list, 'b');
        return $this;
    }

    public function get()
    {
        return join($this->list, ', ');
    }
}

echo ExampleClass::a()->b()->get();

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