class ForLoop
{
private $from;
private $to;
private $vars = [];
function init()
{
$args = func_get_args();
foreach ($args as $arg) {
if (is_array($arg)) {
$key = key($arg);
$value = current($arg);
$this->vars[$key] = $value;
} else {
$this->vars[$arg] = null;
}
}
return $this;
}
function from($from)
{
$this->from = $from;
return $this;
}
function to($to)
{
$this->to = $to;
return $this;
}
public function loop($callback)
{
$callback = $callback->bindTo($this);
for ($i = $this->from; $i <= $this->to; $i++) {
$callback($i);
}
}
function __set($name, $value)
{
if (!array_key_exists($name, $this->vars)) {
throw new Exception("Invalid property: $name");
}
$this->vars[$name] = $value;
}
function __get($name)
{
if ($this->vars[$name]) {
return $this->vars[$name];
}
throw new Exception("Invalid property: " . $property);
}
}
$for = new ForLoop();
$for->init("x", ["y" => 200], ["foo" => "default value"])
->from(1)
->to(10)
->loop(function ($index) {
$this->x = 100;
echo $index + $this->x + $this->y, "\r\n";
});
Created
April 10, 2023 09:07
-
-
Save nezarfadle/79e502ae46c4546a50aea7f80ab8298f to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment