Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a PHP object instance know its name?

Tags:

oop

php

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.

like image 363
eje211 Avatar asked Oct 07 '10 12:10

eje211


2 Answers

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).

like image 160
RichieHindle Avatar answered Oct 10 '22 11:10

RichieHindle


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.

like image 24
Craige Avatar answered Oct 10 '22 11:10

Craige