Search code examples
phpoop

Is there a way to get an object instance name inside a class?


I've got a class for football players called "players", I would like to automatically assign the public variable $name the same name as I called the object instance itself. I know I could do something like this:

class Player {
public $name;
function __construct($name){
$this->name = $name;
}
}

$richarlison = new Player("Richarlison");
$dier = new Player("Dier");

But I was thinking there must be a simpler way, perhaps something like this?(imaginary fnc):

class Player {
public $name;
function __construct(){
$this->name = OBJECT_NAME_FUNCTION();
}
}

$richarlison = new Player();
$dier = new Player();
$kane = new Player();

I'm a beginner and might be thinking about it the wrong way, maybe I shouldn't name objects this way, maybe I shouldn't be using objects for this at all, I do not know.

I was trying to find a way to get a name of an Object using a built_in function inside of the class so that I don't have to type it in and every player is automatically assigned the same name as itself(the object name, the variable)


Solution

  • Of your two examples, the first would be the preferred way to do it:

    $richarlison = new Player("Richarlison");
    $dier = new Player("Dier");
    

    The name attribute is a part of the object, and should be completely unrelated to the name of the variable that contains the object instance:

    $abc = new Player("Richarlison");
    $xyz = new Player("Dier");
    

    In either case, note that it is not very likely that you'll ever hard-code a list of explicitly named objects like this in a real-world program. It's much more likely that you'll take a list of values from a configuration file or a database query, and then maintain them in an array or similar structure.

    Thus, the object should work the same no matter what it's named, and (more importantly) there should be no metadata outside the object -- that defeats the whole point of object oriented programming.

    In addition, you might instantiate an object directly, without ever giving it a name:

    callSomeFunction(new Player('Dier'));
    

    Or your object might be in an array, so it wouldn't have its own name:

    $team = [
        new Player('Richarlison'),
        new Player('Dier'),
        new Player('Kane'),
    ];
    

    Which would be the same as:

    $team = [];
    foreach (['Richarlison', 'Dier', 'Kane'] as $name) {
        $team[] = new Player($name);
    }