Last active
July 23, 2023 04:27
-
-
Save calebporzio/ed3a1edcf0dad1c57909a7c5c01359f2 to your computer and use it in GitHub Desktop.
Handy "chain()" helper method for making non-fluent classes/objects fluent.
This file contains 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 | |
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; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably a guard with
method_exists()
would be sufficient.