Skip to content

Instantly share code, notes, and snippets.

@mattiasghodsian
Last active April 28, 2023 08:39
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 mattiasghodsian/2d66797ff0acc689102144435d1171ed to your computer and use it in GitHub Desktop.
Save mattiasghodsian/2d66797ff0acc689102144435d1171ed to your computer and use it in GitHub Desktop.
Run functions from array
<?php
/**
* Title: Runner
* Author: Mattias Ghodsian
* Description: Run given functions from array
* Donate a cup of coffee: https://www.buymeacoffee.com/mattiasghodsian
* Donate Eth: 0xBBB96204E45D11C9799c6B12E6eE6F0d4A071Ef5
**/
class Runner
{
protected $functions = [];
private $debug;
/**
* __construct
*
* param boolean $debug turn on/off debug
*/
function __construct($debug = false)
{
$this->debug = $debug;
}
/**
* add
*
* param string/array $function string of function or ['class', 'function-name']
* param array $args agruments of given function
* return null
*/
public function add($function, $args = [])
{
if (!is_numeric($function) and !is_integer($function)) {
if (is_string($function) or is_array($function)) {
$this->functions[] = [
'name' => $function,
'args' => $args
];
}else{
die('given function ('.$function.') must be an array or string');
}
}else{
die('given function ('.$function.') must be an array or string');
}
}
/**
* run()
*
* return null
*/
public function run()
{
($this->debug == true ? var_dump($this->functions) : '');
foreach ($this->functions as $key => $function) {
if (!empty($function['args'])) {
call_user_func_array($function['name'], $function['args']);
}else{
call_user_func($function['name']);
}
}
}
}
?>
@mattiasghodsian
Copy link
Author

mattiasghodsian commented Nov 24, 2017

Example:

$runner = New Runner(true);

$runner->add('foobar');
function foobar() {
    echo 'im the '.__FUNCTION__.' function'.PHP_EOL;
}

$runner->add('helloworld');
function helloworld() {
    echo __FUNCTION__.' - '.date('Y', time()).PHP_EOL;
}

$runner->run();

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