检测PHP变量是否是引用/引用 [英] Detecting whether a PHP variable is a reference / referenced

查看:170
本文介绍了检测PHP变量是否是引用/引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中是否有一种方法可以确定给定变量是否是对另一个变量的引用和/或被另一个变量引用?我理解,鉴于评论,设置$a=& $b表示" $ a和$ b在这里完全相等.$ a并不指向$ b,反之亦然.$ a和$ b指向同一个地方."

如果无法确定给定变量是否是引用/引用,是否存在一种通用方法来确定两个变量是否彼此引用?再次,php.net上的评论提供了执行此功能的功能这样的比较-尽管它涉及到编辑一个变量,然后查看另一个变量是否也受到类似的影响.如果可能的话,我宁愿避免这样做,因为我正在考虑的某些变量大量使用了魔术getters/setters.

在这种情况下,请求的背景是编写调试功能以帮助详细查看结构.

解决方案

您可以使用 debug_zval_dump :

function countRefs(&$var) {
    ob_start();
    debug_zval_dump(&$var);
    preg_match('~refcount\((\d+)\)~', ob_get_clean(), $matches);
    return $matches[1] - 4;
}

$var = 'A';
echo countRefs($var); // 0

$ref =& $var;
echo countRefs($var); // 1

但是从PHP 5.4开始,此功能不再起作用,因为它们删除了通过参考支持传递的呼叫时间,并且在较低版本上可能会引发E_STRICT级错误.

如果您想知道上面函数中的-4的来源:您告诉我...我通过尝试获得了它.在我看来,它应该仅为3(变量,函数中的变量,传递给zend_debug_zval的变量),但是我不太擅长PHP的内部结构,并且似乎在途中的某个地方创建了另一个引用. ;)

Is there a way in PHP to determine whether a given variable is a reference to another variable and / or referenced by another variable? I appreciate that it might not be possible to separate detecting "reference to" and "reference from" given the comment on php.net that setting $a=& $b means "$a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place."

If it's not possible to determine whether a given variable is a reference / referenced, is there a generalised way of determining if two variables are references of each other? Again, a comment on php.net supplies a function for doing such a comparison - although it is one that involves editing one of the variables and seeing if the other variable is similarly effected. I'd rather avoid doing this if possible since some of the variables I'm considering make heavy use of magic getters / setters.

The background to the request in this instance is to write a debugging function to help view structures in detail.

解决方案

You can use debug_zval_dump:

function countRefs(&$var) {
    ob_start();
    debug_zval_dump(&$var);
    preg_match('~refcount\((\d+)\)~', ob_get_clean(), $matches);
    return $matches[1] - 4;
}

$var = 'A';
echo countRefs($var); // 0

$ref =& $var;
echo countRefs($var); // 1

This though will not work anymore as of PHP 5.4 as they removed call time pass by reference support and may throw an E_STRICT level error on lower versions.

If you wonder, where the -4 in the above function come from: You tell me... I got it by trying. In my eyes it should be only 3 (the variable, the variable in my function, the variable passed to zend_debug_zval), but I'm not too good at PHP internals and it seems that it creates yet another reference somewhere on the way ;)

这篇关于检测PHP变量是否是引用/引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆