以crossphp中解析注释配置为例,定义协议名:annotate $str_code = array(foo=bar); stream_register_wrapper(annotate,stringToPHPStream); $var=include(annotate://{$str_code}); print_r($var); 这样字符串$str_code就变成了一个php的array,远离eval吧,骚年
以crossphp中解析注释配置为例,定义协议名:annotate
$str_code = 'array("foo"=>"bar")';
stream_register_wrapper("annotate", "stringToPHPStream");
$var = include ("annotate://{$str_code}");
print_r($var);
这样字符串$str_code就变成了一个php的array, 远离eval吧,骚年~
如果要更改示例中协议名称,请更改stringToPHPStream这个类中的stream_open方法
CrossPHP
<?php
include __DIR__.'/stringToPHPStream.php';
$str_code = 'array("foo"=>"bar")';
stream_register_wrapper("annotate", "stringToPHPStream");
$var = include ("annotate://{$str_code}");
print_r($var);
登入後複製
<?php
/**
* 字符串php代码通过wrapper转换为可以执行的php代码
* <pre class="brush:php;toolbar:false">
* 使用方式 stream_register_wrapper("自定义名字", "stringToPHPStream")
* $var = include ("自定义名字://字符串代码")
*
登入後複製
*
* @Auth: wonli
* Class StringToPHPStream
* @package Cross\Lib\Other
*/
class StringToPHPStream {
/**
* 代码内容
*
* @var array
*/
static $content;
/**
* 在$content中的标示
*
* @var string
*/
protected $key;
/**
* @var int
*/
protected $pos;
/**
* @param $path
* @param $mode
* @param $options
* @param $opened_path
* @return bool
*/
public function stream_open($path, $mode, $options, $opened_path) {
$this->key = md5($path);
if (! isset(self::$content[$this->key])) {
self::$content[$this->key] = sprintf('pos = 0;
return true;
}
/**
* @param $count
* @return string
*/
public function stream_read($count) {
$content = self::$content[$this->key];
$ret = substr($content, $this->pos, $count);
$this->pos += strlen($ret);
return $ret;
}
/**
*
*/
public function stream_stat() {
}
/**
*
*/
public function stream_eof() {
}
}