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)
2
Answers
You can store the names in an array, then store the objects in another array.
Loop through the names, and set the objects in another array with the names.
So using this code, after the loop you would access each player like:
$players["Dier"]
etcOf your two examples, the first would be the preferred way to do it:
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: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:
Or your object might be in an array, so it wouldn’t have its own name:
Which would be the same as: