-
See: Macroable call public function __call($method, $parameters)
{
if (! static::hasMacro($method)) {
throw new BadMethodCallException(sprintf(
'Method %s::%s does not exist.', static::class, $method
));
}
$macro = static::$macros[$method];
if ($macro instanceof Closure) {
$macro = $macro->bindTo($this, static::class);
}
return $macro(...$parameters);
} I have come to understand that this is a method related to macro definitions. When I attempt with the following content: class Demo{
public function whereLike(string $column, string $value, string $boolean = 'and'): Builder
{
return $this->where($column,'like','%'.$value.'%',$boolean);
}
}
Builder::macro('whereLike',[new Demo,'whereLike'); Registering a function in this manner. When I use public function __call($method, $parameters)
{
if (! static::hasMacro($method)) {
throw new BadMethodCallException(sprintf(
'Method %s::%s does not exist.', static::class, $method
));
}
$macro = static::$macros[$method];
if ($macro instanceof Closure) {
return $macro->call($this,$parameters);
}
return $macro(...$parameters);
} That's it. if ($macro instanceof Closure) {
return $macro->call($this,$parameters);
} I have achieved the desired effect, but I am not sure if it's due to an improper use of the method or a hidden bug. Can anyone help clarify my doubt? Thank you very much. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
When I attempt to use $closure = (new Demo)->$method(...);
var_dump($closure); // \Closure
$closure = \Closure::bind($closure,null);
var_dump($closure); // null |
Beta Was this translation helpful? Give feedback.
-
what you want is using mixins. class Demo{
public function whereLike(): Closure
{
return function(string $column, string $value, string $boolean = 'and'): Builder
{
return $this->where($column,'like','%'.$value.'%',$boolean);
};
}
} Builder::mixin(new Demo()); When $this is bound to a class on instance, it can't be rebound. |
Beta Was this translation helpful? Give feedback.
It's your undersrtanding. It is not a bug.