Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the name of a calling var

Tags:

php

Anyone has an idea if this is at all possible with PHP?

function foo($var) {
    // the code here should output the value of the variable
    // and the name the variable has when calling this function
}

$hello = "World";
foo($hello);

Would give me this output

varName = $hello
varValue = World

EDIT

Since most people here 'accuse' me of bad practices and global variables stuff i'm going to elaborate a little further on why we are looking for this behaviour.

the reason we are looking at this kind of behaviour is that we want to make assigning variables to our Views easier.

Most of the time we are doing this to assign variables to our view

$this->view->assign('products', $products);
$this->view->assign('members', $members);

While it would be easier and more readable to just be able to do the following and let the view be responsible to determining the variable name the assigned data gets in our views.

$this->view->assign($products);
$this->view->assign($members);
like image 622
ChrisR Avatar asked Feb 02 '10 12:02

ChrisR


1 Answers

Short answer: impossible.

Long answer: you could dig through apd, bytekit, runkit, the Reflection API and debug_backtrace to see if any obscure combination would allow you to achieve this behavior.

However, the easiest way is to simply pass the variable name along with the actual variable, like you already do. It's short, it's easy to grasp, it's flexible when you need the variable to have a different name and it is way faster than any possible code that might be able to achieve the other desired behavior.

Keep it simple

removed irrelevant parts after OP edited the question

like image 164
Gordon Avatar answered Nov 03 '22 01:11

Gordon