skip to Main Content

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


  1. 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"] etc

    class Player {
            public $name;
            function __construct($name){
                $this->name = $name;
            }
        }
    
        $names = ["Richarlison","Dier"];
        $players = [];
    
        foreach($names as $name){
            $players[$name] = new Player($name);
        }
    
    Login or Signup to reply.
  2. 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");
    

    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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search