func(CONST_A)
should return 'CONST_A'
, func($name)
should return $name
How to implement this func
in PHP?
func(CONST_A)
should return 'CONST_A'
, func($name)
should return $name
How to implement this func
in PHP?
Try this:
<?php
function getVarConst($var)
{
if (isset($GLOBALS[$var]) // check if there is a variable by the name of $var
{
return $GLOBALS[$var]; // return the variable, as it exists
}
else if (defined($var)) // the variable didn't exist, check if there's a constant called $var
{
return constant($var); // return the constant, as it exists
}
else
{
return false; // return false, as neither a constant nor a variable by the name of $var exists
}
}
?>
This doesn't seem possible easily.
You can use reflection to determine the parameters of the function, but that returns the variable names that the function expects, and if you're already inside the function, you kind of already know those.
debug_backtrace
is the usual way of peeking at what called you, but it returns the values of the passed arguments, not the variable names or constants that the caller used when making the call.
However, what it does give you is the file name and line number of the caller, so you could open up the file and seek to that line and parse it out, but that would be very silly and you should not do this. I am not going to give you example code for this, as it is so utterly silly that you should not consider doing it ever.
The get_defined_vars
thing is a hack and is not guaranteed to work either, and definitely won't work for constants, as get_defined_constants
does that.
This isn't possible.
You literally want the following right?
define('CONST_A', 'THIS COULD BE ANYTHING');
$name = 'who cares';
func(CONST_A); //returns 'CONST_A'
func($name); //returns '$name'
The function can't know that.
I suppose that reading the source code like Charles describes could get you this, but why?