Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created February 25, 2019 11:59
Show Gist options
  • Save kobus1998/b821c502b789a8f9f74180fc05241d5f to your computer and use it in GitHub Desktop.
Save kobus1998/b821c502b789a8f9f74180fc05241d5f to your computer and use it in GitHub Desktop.
Trait that catches custom methods that are not in the class
<?php
trait CustomFunctionality
{
protected $functions = [];
public function addMethod(string $name, callable $function)
{
$this->functions[$name] = $function;
return $this;
}
public function __call(string $name, array $params)
{
if (isset($this->functions[$name])) {
return \call_user_func_array($this->functions[$name], $params);
}
}
}
class Test
{
use \CustomFunctionality;
}
$t = new Test();
$t->addMethod('toLower', function ($str) {
return strtolower($str);
});
echo $t->toLower('ABC'); // abc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment