tags:

views:

131

answers:

10

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);
+5  A: 

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

Gordon
very very close to giving you a +1 for this, except for the fact that you went past the short answer. It's impossible and for good reason.
nickf
@nickf Well, never say never, right? The thing is, the extensions I've linked are very powerful and allow reverse engineering at runtime. There is chance you *could* achieve what the OP wants to do with them in some weird way, e.g. like @symcbean suggested. It's just not feasible or worth the effort.
Gordon
+2  A: 

I don't think there is any language where this is possible. That's simply not how variables work. There is a difference between a variable and the value it holds. Inside the function foo, you have the value, but the variable that held the value is not available. Instead, you have a new variable $var to hold that value.

Look at it like this: a variable is like a bucket with a name on it. The content (value) of the variable is what's inside the bucket. When you call a function, it comes with its own buckets (parameter names), and you pour the content of your bucket into those (well, the metaphor breaks down here because the value is copied and still available outside). Inside the function, there is no way to know about the bucket that used to hold the content.

Michael Borgwardt
A: 

impossible - the max. ammount of information you can get is what you see when dumping

debug_backtrace();
roman
+2  A: 

What you're asking isn't possible. Even if it was, it would likely be considered bad practice as its the sort of thing that could easily get exploited.

If you're determined to achieve something like this, the closest you can get would be to pass the variable name as a string and reference it in the function from the $GLOBALS array.

eg

function this_aint_a_good_idea_really($var) {
    print "Variable name: {$var}\n";
    print "Variable contents: {$GLOBALS[$var]}\n";
}
$hello="World";
this_aint_a_good_idea_really('hello');

But as I say, that isn't really a good idea, nor is it very useful. (Frankly, almost any time you resort to using global variables, you're probably doing something wrong)

Simon C
+1 : I was just typing something similar...
jeroen
The fact that i'm asking this is because i don't want to resolve to global vars. I'm trying to stay away from them as far as possible actually and was wondering if there was an easier way of achieving what i wanted. I've updated the OQ with the scenario we are facing atm
ChrisR
+1  A: 

Its not impossible, you can find where a function was invoked from debug_backtrace() then tokenize a copy of the running script to extract the parameter expressions (what if the calling line is foo("hello $user, " . $indirect($user,5))?),

however whatever reason you have for trying to achieve this - its the wrong reason.

C.

symcbean
+3  A: 

Regardless of my doubt that this is even possible, I think that forcing a programmer on how to name his variables is generally a bad idea. You will have to answer questions like

Why can't I name my variable $arrProducts instead of $products ?

You would also get into serious trouble if you want to put the return value of a function into the view. Imagine the following code in which (for whatever reason) the category needs to be lowercase:

$this->view->assign(strtolower($category)); 

This would not work with what you're planning.

My answer therefore: Stick to the 'verbose' way you're working, it is a lot easier to read and maintain.

If you can't live with that, you could still add a magic function to the view:

public function __set($name, $value) {
    $this->assign($name, $value);
}

Then you can write

$this->view->product = $product;
Cassy
+1 for `__set` as an alternative. Wasn't mentioned before. Although he could just as well write $this->view->product = 'foo'. It would create $product as a public member of view. He needs __set only if this is too deviate from the regular behavior.
Gordon
A: 

Maybe what you want to do is the other way around, a hackish solution like this works fine:

<?php
  function assign($val)
  {
    global $$val;
    echo $$val;
  }
  $hello = "Some value";
  assign('hello');

Ouputs: Some value

Kristoffer S Hansen
I see you said you dont want anything to do with globals, let me try and come up with something else
Kristoffer S Hansen
+1  A: 

Okay, time for some ugly hacks, but this is what I've got so far, I'll try to work on it a little later

<?php
class foo
{
    //Public so we can test it later
    public $bar;
    function foo()
    {
        //Init the array
        $this->bar = array();
    }
    function assign($__baz)
    {
        //Try to figure out the context
        $context = debug_backtrace();
        //assign the local array with the name and the value
        //Alternately you can initialize the variable localy
        //using $$__baz = $context[1]['object']->$__baz;
        $this->bar[$__baz] = $context[1]['object']->$__baz;
    }
}
//We need to have a calling context of a class in order for this to work
class a
{
    function a()
    {

    }
    function foobar()
    {
        $s = "testing";
        $w = new foo();
        //Reassign local variables to the class
        foreach(get_defined_vars() as $name => $val)
        {
            $this->$name = $val;
        }
        //Assign the variable
        $w->assign('s');
        //test it
        echo $w->bar['s'];
    }
}
//Testrun
$a = new a();
$a->foobar();
Kristoffer S Hansen
Note, you can then later extract the variables using... `extract($this->bar)` which will pull the variables from the associative array into the defined variables
Kristoffer S Hansen
A: 

What you wish to do, PHP does not intend for. There is no conventional way to accomplish this. In fact, only quite extravagant solutions are available. One that remains as close to PHP as I can think of is creating a new class.

You could call it NamedVariable, or something, and as its constructor it takes the variable name and the value. You'd initiate it as $products = new NamedVariable('products', $productData); then use it as $this->view->assign($products);. Of course, your declaration line is now quite long, you're involving yet another - and quite obscure - class into your code base, and now the assign method has to know about NamedVariable to extract both the variable name and value.

As most other members have answered, you are better off suffering through this slight lack of syntactic sugar. Mind you, another approach would be to create a script that recognizes instances of assign()'s and rewrites the source code. This would now involve some extra step before you ran your code, though, and for PHP that's silly. You might even configure your IDE to automatically populate the assign()'s. Whatever you choose, PHP natively intends no solution.

erisco
A: 

This solution uses the GLOBALS variable. To solve scope issues, the variable is passed by reference, and the value modified to be unique.

function get_var_name(&$var, $scope=FALSE) {
    if($scope) $vals = $scope;
    else      $vals = $GLOBALS;
    $old = $var;
    $var = $new = 'unique'.rand().'value';
    $vname = FALSE;
    foreach ($vals as $key => $val) {
        if($val === $new) $vname = $key;
    }
    $var = $old;
    return $vname;
}

$testvar = "name";
echo get_var_name($testvar);  // "testvar"

function testfunction() {
    $var_in_function = "variable value";
    return get_var_name($var_in_function, get_defined_vars());
}

echo testfunction();  // "var_in_function"

class testclass {
    public $testproperty;
    public function __constructor() {
        $this->testproperty = "property value";
    }
}

$testobj = new testclass();
echo get_var_name($testobj->testproperty, $testobj);  // "testproperty"
pixelbath