在PHP7上,您可以使用下面的代码获取给定id的资源:
function fetchResourcePHP7($id){
if(!is_int($id)) return false;
foreach(get_resources() as $v){
if(intval($v)==$id) return $v;
}
return false;
}
在PHP5上,您可以使用这个自定义递归函数来实现相同的功能
function fetchResource5($id,$array=array(),$restart=true){
static $result=false;
if($restart) $result=false;
if(is_resource($result)) return $result;
if(!is_array($array)) return false;
if(!is_int($id)) return false;
$avoid=['_GET'=>0,'_POST'=>0,'_FILES'=>0,'_REQUEST'=>0,'GLOBALS'=>0,'_COOKIE'=>0];
if(!$array){
foreach($GLOBALS as $k=>$v){
if(is_resource($v)&&intval($v)==$id){
$result=$v;
}
elseif(is_array($v)&&!isset($avoid[$k])){
fetchResource($id,$v,false);
}
}
}
else{
foreach($array as $k=>$v){
if(is_resource($v)&&intval($v)==$id){
$result=$v;
}
elseif(is_array($v)&&!isset($avoid[$k])){
fetchResource($id,$v,false);
}
}
}
return $result;
}
函数中的用法很简单:
function any($var){
$onevar='';
$anothervar='';
//an useless example of fetch row here,you could provide $GLOBALS array instead of local variables
$someresource=fopen('sometext.txt','r');
$getresource=fecthResource5(5,get_defined_vars());//always ignore the third argument ,the id 5 is just an example
return true;
}
在全局上下文中,用法更为简单:
var_dump(fetchResource5(36));//if a resource with id 36 exists it will dump it