How to get instance ID with PHP

2019-06-28 02:19发布

问题:

I'm looking for a way to get the instance ID of a given object / resource with PHP, the same way var_dump() does:

var_dump(curl_init()); // resource #1 of type curl
var_dump(curl_init()); // resource #2 of type curl

How can I get the instance count without calling var_dump()? Is it possible?

回答1:

Convert it to an int to get the resource ID:

$resource= curl_init();
var_dump($resource);
var_dump(intval($resource));


回答2:

(int) curl_init()


回答3:

This is a very interesting question... I would be interested to see what you would use this for... but here is one way...

<?php 
$ch = curl_init();
preg_match("#\d+#", (string) $ch, $matches);
$resourceIdOne = end($matches);


$ch2 = curl_init();
preg_match("#\d+#", (string) $ch2, $matches);
$resourceIdTwo = end($matches);
?>


回答4:

Convert resource to id with sprintf()

$resource = curl_init();
$id = sprintf('%x', $resource);

// mimic var_dump();
$type = get_resource_type($resource);
echo "resource({$id}) of type ({$type})\n";


回答5:

function get_resource_id($resource) {
    if (!is_resource($resource))
        return false;

    return array_pop(explode('#', (string)$resource));
}