Skip to content

Instantly share code, notes, and snippets.

@sybrew
Created March 13, 2018 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sybrew/034059824dbba4f49bfbbff36df184f2 to your computer and use it in GitHub Desktop.
Save sybrew/034059824dbba4f49bfbbff36df184f2 to your computer and use it in GitHub Desktop.
A readable if this-then-that-and-else-this-then-that-and... function wrapper.
<?php
function if_( $value ) {
return new class( (bool) $value ) {
public $run, $and;
public $cb = [];
function __construct( $run ) { $this->run = $run; }
function __destruct() {
foreach ( $this->cb as $cb ) {
$cb ? $cb() : null;
}
}
function then_( $cb ) {
if ( $this->run ) {
$this->cb[] = $cb;
$this->run = false;
$this->and = true;
} else {
$this->run = true;
$this->and = false;
}
return $this;
}
function else_( $cb ) {
return $this->then_( $cb );
}
function and_( $cb ) {
if ( $this->and ) {
$this->run = true;
$this->and = false;
} else{
$this->run = false;
$this->and = false;
}
return $this->then_( $cb );
}
};
}
/**
* Example:
*/
if_( true )->then_( '_do' )->and_( '_do_that' )->else_( '_dont' )->and_( '_dont_that' );
echo "\n";
if_( false )->then_( '_do' )->and_( '_do_that' )->else_( '_dont' )->and_( '_dont_that' );
function _do() {
print 'yay1';
}
function _do_that() {
print '-yay2';
}
function _dont() {
print 'nay1';
}
function _dont_that() {
print '-nay2';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment