Skip to content

Instantly share code, notes, and snippets.

@imliam
Last active January 15, 2020 14:30
Show Gist options
  • Save imliam/11940ab73b024140f8e7cd76ef56b0e0 to your computer and use it in GitHub Desktop.
Save imliam/11940ab73b024140f8e7cd76ef56b0e0 to your computer and use it in GitHub Desktop.
Run functions consecutively by piping through the result of one into the next.
<?php
if (! function_exists('take')) {
/**
* Run functions consecutively by piping through the result of one
* into the next.
*
* @param mixed $value A value
*
* @return object
*/
function take($value)
{
return new class($value) {
public function __construct($value)
{
$this->id = '__pipe-' . uniqid();
$GLOBALS[$this->id] = $value;
}
public function __destruct()
{
unset($GLOBALS[$this->id]);
}
public function pipe($value)
{
$GLOBALS[$this->id] = $value;
return $this;
}
public function __get($name)
{
if ($name === 'value') {
return $GLOBALS[$this->id];
}
trigger_error("Property '$name' doesn't exist and cannot be gotten", E_USER_ERROR);
}
};
}
}
@imliam
Copy link
Author

imliam commented Feb 23, 2018

Example usage:

$taken = take('HeLLo, WoRld.');

$taken->pipe(strtolower($taken->value))
      ->pipe(ucfirst($taken->value));

echo $taken->value; // 'Hello world.'

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