How to get instance ID with PHP

ε祈祈猫儿з 提交于 2019-12-12 11:35:37

问题


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));
}


来源:https://stackoverflow.com/questions/1853622/how-to-get-instance-id-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!