11

If I have code like this:

class Person {
    $age;
    $height;
    $more_stuff_about_the_person;

    function about() {
        return /* Can I get the person's name? */;
    }
}

$John = new Person();
$Peter = new Person();

print $John->about();  // Print "John".
print $Peter->about(); // Print "Peter".

Is it possible to print the person's name, stored as the variable name, from the method?

As it's not standard procedure, I'm guessing it's a bad idea.

I've looked it up and I can't find anything about it.

11
  • It would be useful in some cases but i'm afraid this isn't possible. Maybe it is with variable variables? Commented Oct 7, 2010 at 12:29
  • 2
    Should a Person not a have an instance variable $name? What if you have objects in an array like $p = array(new Person(), new Person()) ? Commented Oct 7, 2010 at 12:31
  • 1
    There might be an awfully kludgy way using debug_backtrace() (which will give you the line the about() call was made from) and the tokenizer (which may give you the variable reference the call was made for) but it's not really suitable for production use Commented Oct 7, 2010 at 12:36
  • 2
    (nitpick) that's not the object instance name, but the name of the variable the object instance is assigned to. Commented Oct 7, 2010 at 12:38
  • 1
    @Mark actually you can do that with ${"Maureen O'Hara"} = new StdClass; $firstName = 'Maureen'; $lastName = "O'Hara"; var_dump( ${"$firstName $lastName"} ); :D Commented Oct 7, 2010 at 12:57

4 Answers 4

19

No. Objects can have multiple names, or no names. What would happen here:

$John = new Person();
$Richie = $John;      // $John and $Richie now both refer to the same object.
print $Richie->about();

or here:

function f($person)
{
    print $person->about();
}

f(new Person());

If the objects need to know their own names, then they need to explicitly store their names as member variables (like $age and $height).

Sign up to request clarification or add additional context in comments.

5 Comments

you can have a property though and just set that property when you initialise the class. Obviously if you know the name of the variable you are assigning it to then you will know the name. Plus, in the interest of logic, if you know the name of the variable to retrieve the object then you will know the name anyway... :/
In my real-world example, the instance name and the value of the "name" property would have always been the same, and so it seemed redundant. But based on these examples, it now see that it is not redundant at all.
@eje211 - even more important if you created a $persons array: $persons = array('John' => new Person('John'), 'Jane' => new Person('Jane'));
@Mark Baker: Then, the name would be the array's key. But I see now it would still be a Very Bad Idea.
Nice example. It would be helpfull in some way if the class has a way of knowing from which variable or instance it was called. e.g. from $Richie->about() or from $John->about().
2

Eje211, you're trying to use variables in very bizarre ways. Variables are simply data holders. Your application should never care about the name of the variables, but rather the values contained within them.

The standard way to accomplish this - as has been mentioned already, is to give the Person class a 'name' property.

Just to re-iterate, do not rely on variable names to determine the output/functionality of your application.

2 Comments

You are making a claim without even bothering to try to back up your claim with reasons. It may as well just be random noise. I agree it is not standard practice, but to say this is never a good idea is narrow minded. It would be very useful in an internal DSL. I agree there may be no way to do this, but you are saying nobody should want to do this.
True about "...trying to use ... in very bizarre..." or perhaps a more neutral statement is " trying to use ... in very unexpected" if that strikes you as such. However, one very excellent use case is Automation or Code Creation tools which would or could very much care about variable names; even the PHP language itself has a feature such as $$var which supports/facilitates dynamic variable names.
0

User defined variables names should be treated as totally transparent to the PHP compiler (or any compiler for that matter). The objects you create are just references to memory that point to the real object. Their name has no meaning. Name is a member of person.

You can, however, get the variables you want with get_defined_vars()

foreach (get_defined_vars() as $key => $val) {
   if ($val instanceof Person) {
      echo $key;
   }
}

This should absolutely not be done, however, and the object would still need to know the order in which the variables were stored. No idea how you would calculate that.

2 Comments

It is not true that the names of variables have no meaning. If that were true we would give them random names or maybe they would have no name at all or the name would be hidden from the programmer. They are a form of communication and they can mean whatever we want them to mean within what the language supports. I wish there was a well supported way to do what the question is asking.
@still_dreaming_1 It is true, it depends on your point of view. The compiler absolutely doesn't care if you name your variables after your ex-girlfriends, ex-wives or the complete cast of all seasons of Game of Thrones. It is the first level of interpretation, namely you, the person writing it. Now if we share code, and I have no frigging clue who your ex-girlfriends or ex wives were and there meaning, I cannot interpretate your code. It means I cannot understand your interpretation of a programming language. It becomes useless to me, but not for the compiler ..
0

This example might be helpful currently there is no method that tells you the object name you have to specify yourself like in the code below:

class Person {

    public $age=0;
    public $height=0;
    public $objPerson='';

    function about($objPerson,$age,$height) {
        return 
                'Person Object Name: '.$objPerson.'<br>'.
                'Age: '.$age.'<br>'.
                'height: '.$height.'ft<br><hr>';
    }
  }

$John = new Person();

$Peter = new Person();

print $John->about('John',25,'5.5'); 

print $Peter->about('Peter',34,'6.0'); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.