代码之家  ›  专栏  ›  技术社区  ›  clarkk

按唯一id获取活动资源

php
  •  0
  • clarkk  · 技术社区  · 6 年前

    我有多种资源。。有些是套接字和其他fopen处理程序。。

    $handle = fopen('file', 'w');
    print_r($handle);
    

    将输出

    Resource id #20
    

    intval($handle);

    有没有可能把它倒过来。。如果您有ID,是否可以获取资源?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Elementary    6 年前

    在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