Skip to content

Instantly share code, notes, and snippets.

@abiusx
Created April 25, 2016 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abiusx/a6ef8d536262bd720011460db8c50424 to your computer and use it in GitHub Desktop.
Save abiusx/a6ef8d536262bd720011460db8c50424 to your computer and use it in GitHub Desktop.
An implementation of is_ref in PHP
<?php
/**
* This is a hacky is_ref function.
* Determines whether a variable is a reference or not
* by using var_dump on its symbol table and
* checking whether it has '&' before its value or not.
* @param array $defined_vars should send get_defined_vars() to this. enforced.
* @param mixed $var any variable, should be a variable and not a expression
* @return boolean
*/
function _is_ref($defined_vars=[],$var)
{
$t=&debug_backtrace()[0];
preg_match("/".__FUNCTION__."\(\s*get_defined_vars\s*\(\s*\)\s*,\s*\\$(.*?)\)/i", file($t['file'])[$t['line']-1],$varname);
if ($varname)
$varname=$varname[1];
else
{
trigger_error("You need to provide two arguments to '".__FUNCTION__.
"', namely get_defined_vars() and a variable");
return false; //an expression is not a reference
}
foreach ($defined_vars as $k=>$v)
if ($k!==$varname)
unset($defined_vars[$k]);
ob_start();
var_dump($defined_vars);
$dump=ob_get_clean();
if (($r=strpos($dump,"=>\n &"))===false)
return false;
else
{
if ($r>=17+strlen($varname) /*array(_) {\n ["_"]*/
and $r<20+strlen($varname))
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment