How to check if variable was passed by reference in PHP

可紊 提交于 2020-01-03 17:17:30

问题


Straightforward: I want to write some code which tells if a variable was passed by reference or not. For example:

<?php
function isReference($variable) {
    //return TRUE if &$something was passed
    //return FALSE if $something was passed
}
$text = 'Anything';
$a = isReference(&$text); //return TRUE
$b = isReference($test); //return FALSE
?>

For those who are curious - why do I need it? Firstly I do not like to leave problems unsolved. Secondly, I am currently enhancing by skills by writing an extension to mysqli, which would prepare statements similar to how PDO does. If anybody knows the difference between bindParam and bindValue in PDO, they know that it's a workaround of this question. I can just make two functions, but I wonder if it's possible with one.

Thanks in advance.


回答1:


Here's a way to do it without using the debug_zval_dump function:

function isReference($variable) {
    $variable = array($variable);
    $arg = func_get_arg(0);
    $isRef = isset($arg[0]) && $arg === array($variable[0]);
    $variable = $variable[0];

    return $isRef;
}

Note: there is only a single case when this will not work:

$text = array(&$text); // although i don't see why such a structure could be used
isReference($text); // will wrongly return false

Obviously you can bypass this limitation by using a random unique key (instead of 0).




回答2:


You can use debug_zval_dump to dump a string representation of an internal zend value to output:

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

$var1 = 'Var1';
$var2 = &$var1; // passed by ref
if(isRef($var2)) echo 'Passed by ref';

But be aware of PHP - 5.4.




回答3:


Simply checking for the default value seems to work fine in my tests. Obviously it wont work if $t is already set to 'x' but you could change the default value to something totally unlikely to workaround this:

function test(&$t='x'){
   if($t!='x') $t = 2;
}
test();   echo $t;  //outputs: null
test($t); echo $t;  //outputs: 2


来源:https://stackoverflow.com/questions/21958610/how-to-check-if-variable-was-passed-by-reference-in-php

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