• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • get_resource_type()

    (PHP 4 >= 4.0.2, PHP 5, PHP 7)

    返回资源(resource)类型

    描述

    get_resource_type(resource $handle): string

    此函数返回一个字符串,用于表示传递给它的resource的类型。如果参数不是合法的resource,将产生错误。

    <?php
    $c = mysql_connect();
    echo get_resource_type($c)."\n";
    // 打印:mysql link
    $fp = fopen("foo","w");
    echo get_resource_type($fp)."\n";
    // 打印:file
    $doc = new_xmldoc("1.0");
    echo get_resource_type($doc->doc)."\n";
    // 打印:domxml document
    ?>
    
    Try this to know behavior:
    <?php
    function resource_test($resource, $name) {
      echo 
        '[' . $name. ']',
        PHP_EOL,
        '(bool)$resource => ',
        $resource ? 'TRUE' : 'FALSE',
        PHP_EOL,
        'get_resource_type($resource) => ',
        get_resource_type($resource) ?: 'FALSE',
        PHP_EOL,
        'is_resoruce($resource) => ',
        is_resource($resource) ? 'TRUE' : 'FALSE',
        PHP_EOL,
        PHP_EOL
      ;
    }
     
    $resource = tmpfile();
    resource_test($resource, 'Check Valid Resource');
     
    fclose($resource);
    resource_test($resource, 'Check Released Resource');
     
    $resource = null;
    resource_test($resource, 'Check NULL');
    ?>
    It will be shown as...
    [Check Valid Resource]
    (bool)$resource => TRUE
    get_resource_type($resource) => stream
    is_resoruce($resource) => TRUE
    [Check Released Resource]
    (bool)$resource => TRUE
    get_resource_type($resource) => Unknown
    is_resoruce($resource) => FALSE
    [Check NULL]
    (bool)$resource => FALSE
    get_resource_type($resource) => FALSE
    Warning: get_resource_type() expects parameter 1 to be resource, null given in ... on line 10
    is_resoruce($resource) => FALSE
    In PHP5 (on Linux), the above example identifies the "file" handler as a 'stream', not 'file'.
    This can be particularly worrisome if you're trying to determine the type of stream using this function.
    The alternative is to use <?php stream_get_meta_data() ?>, which returns an array containing "stream_type (string) - a label describing the underlying implementation of the stream."
    Furthermore, this function returns 'stream' on php 4.3 on windows & linux.
    You if you want to differentiate between a file resource and other stream resources, as stated before stream_get_meta_data() gives you an array which, on my system, contains the following elements which might suggest a file handle:
    [wrapper_type] => plainfile
    [stream_type] => STDIO
    However I've only compared this to a stream from a url, so I include this only as a suggestion.
    This function will generate an error and return NULL instead FALSE in the next example:
    <?php
    $var = 3;
    var_dump(get_resource_type($var));
    ?>
    

    上篇:get_defined_vars()

    下篇:gettype()