Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handy "chain()" helper method for making non-fluent classes/objects fluent.
<?php
function chain($object)
{
return new class ($object) {
protected $lastReturn = null;
public function __construct($object)
{
$this->wrapped = $object;
}
public function __toString()
{
return (string) $this->lastReturn;
}
public function __call($method, $params)
{
if (($index = array_search('{carry}', $params)) !== false) {
$params[$index] = $this->lastReturn;
}
$this->lastReturn = $this->wrapped->{$method}(...$params);
return $this;
}
};
}
@guilhermeportela
Copy link

guilhermeportela commented Jan 30, 2019

It will always throw a BadMethodCallException, won't it?

@guilhermeportela
Copy link

guilhermeportela commented Jan 30, 2019

It will always throw a BadMethodCallException, won't it?

Probably a guard with method_exists() would be sufficient.

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