Skip to content

Instantly share code, notes, and snippets.

@hibariya
Created June 4, 2010 04:36
Show Gist options
  • Save hibariya/424955 to your computer and use it in GitHub Desktop.
Save hibariya/424955 to your computer and use it in GitHub Desktop.
<?php
class Bloc
{
private $source;
private $id;
private $args;
public function __construct($source, Array $args=null)
{
$this->source = $source;
$this->args = $args? $args: array();
do{
$id = mt_rand();
if(!array_key_exists($id, $GLOBALS)){
$this->id = $id;
$GLOBALS[$this->id] = array();
}
}while(!$this->id);
}
public function id(){ return $this->id; }
public function __get($name){ return $GLOBALS[$this->id][$name]; }
public function __set($name, $value){ return $GLOBALS[$this->id][$name] = $value; }
private function before_call($args)
{
$this->args = array_merge(array_merge($GLOBALS, $GLOBALS[$this->id]), $this->args);
$this->args = array_merge($this->args, (array)array_shift($args));
unset($this->args[$this->id]);
}
private function after_call()
{
$this->args = array();
}
public function call()
{
$this->before_call((array)func_get_args());
$ignore_keys = array('ignore_keys', 'GLOBALS', '___n', '___v', '___r', $this->id);
foreach($this->args as $___n => $___v){
if(!in_array($___n, $ignore_keys))
$$___n = $___v;
}
unset($___n, $___v);
$___r = eval($this->source);
foreach(get_defined_vars() as $___n => $___v){
if(!in_array($___n, $ignore_keys)){
if(!(array_key_exists($___n, $GLOBALS)&&$GLOBALS[$___n]===$___v))
$GLOBALS[$this->id][$___n] = $___v;
}
}
$this->after_call();
return $___r;
}
}
define('called', false);
function bloc($args=null, $trace=null){
if(!$trace) $trace = debug_backtrace();
$caller = array_shift($trace);
$block_part = join(array_splice(file($caller['file']), $caller['line']));
preg_match('/.+\};/smi', $block_part, $matches);
$block = array_shift(explode('};', array_shift($matches)));
return new Bloc($block, $args);
}
/*{{{*
// Examples for Bloc
$b = bloc(array('hoge'=>10));if(called){
$piyo = 'piyo';
if(!isset($hoge)) $hoge = 0;
$hoge++;
return array($hoge, $piyo);
};
var_dump($b->call());
var_dump($b->call());
$hoge = 10;
var_dump($b->call(get_defined_vars()));
var_dump($b->call());
var_dump($b->id());
class MyArray
{
private $raw;
public function __construct(Array $raw)
{
$this->raw = $raw;
}
public function each($args=null)
{
$block = bloc($args, debug_backtrace());
$ret = null;
for($i=0;$i<count($this->raw);$i++){
$ret = $block->call(array('key'=>$i, 'value'=>$this->raw[$i]));
}
return null;
}
}
function in_function()
{
$c = bloc();if(called){
if(!isset($foo)) $foo = 'piyo';
$foo++;
return $foo;
#var_dump(get_defined_vars());
};
$ma = new MyArray(array(9,423,6,4567,7878,634,3,7,45,754,745));
if($ma->each(get_defined_vars())){
$p = $c->call();
print("${p}, ${key}, ${value}\n");
};
}
in_function();
/*}}}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment