|
|
|
|
||||||
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 |
|
Messages: n/a
Hébergeur: |
Anyway to do it? I know you can use a variable's contents as a
variable name with $$name, but I'd like to do it the other way around. <?php function foo($bar) { return $bar; } $name = foo($variable_name); ?> I'd like the function foo to return a string of the variable name passed to it, in this case 'variable_name'. A friend of mine who does C ++ programming says that pointers are the way to go here, but as far as I know PHP doesn't support them. |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
BoneIdol wrote:
> I'd like the function foo to return a string of the variable name > passed to it, in this case 'variable_name'. A friend of mine who does > C ++ programming says that pointers are the way to go here, but as far > as I know PHP doesn't support them. > A (not fullproof) way is the following: function foo($bar) { $keys = array_keys($GLOBALS); $values = array_values($GLOBALS); $index = array_search($bar, $values, true); if ($index !== false) { return $keys[$index]; } } $variable_name = 'foo'; $name = foo($variable_name); print $name; Of course, this only works when each variable has a unique value... JW |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
Also sprach BoneIdol:
> Anyway to do it? No. You could try this (not tested, though): $foo = 'bar'; doSomething( compact( 'foo' ) ); function doSomething( $aVar ) { list( $sVarName, $xVarValue ) = each( $aVar ); echo "The variable is called $sVarName and has the value $xVarValue.\n"; } With objects in PHP5 you can use the __set()/__get()/__call() magic functions (not tested either): class Foo { private $_aVars = array(); public function __set( $sName, $xValue ) { echo "Setting $sName to value $xValue.\n"; $this->_aVars[$sName] = $xValue; } public function __get( $sName ) { echo "Getting $sName.\n"; return $this->_aVars[$sName]; } } $oFoo = new Foo; $oFoo->bar = 'baz'; echo $oFoo->bar; But why do you need such a functionality? Maybe there is a solution to your problem (whatever it is) which does not require it? Greetings, Thomas |
|
![]() |
| Outils de la discussion | |
|
|