Until now, I feel that I have understood the concept and benefits of OOP programming, and I actually have not had any difficulty understanding how to work with classes in PHP.
However, this confused me a little. I think I can understand it, but I'm still not sure.
I follow a set of video tutorials (not sure about the rules for connecting to external resources, but I found them on youtube), and they are pretty clear. It is also frustrating when the tutor decided to pass one class as a parameter to another class. At least I think what is happening;
Class Game { public function __construct() { echo 'Game Started.<br />'; } public function createPlayer($name) { $this->player= New Player($this, $name); } } Class Player { private $_name; public function __construct(Game $g, $name) { $this->_name = $name; echo "Player {$this->_name} was created.<br />"; } }
Then I create an object of the Game class and call its method;
$game = new Game(); $game-> createPlayer('new player');
On the contrary, the teacher does not explain why he did it, and did not show, as far as I see, any calls in the code that would justify it.
Is the constructor of the magic method in Pass passing in the Game class as a reference? Does this mean that the entire class is available in the Player class by reference? When referring to $ this, without pointing to any specific method or property, do you refer to the entire class?
If this is what happens, then why should I do this? If I created a Player inside my Game Class, then of course I can just access my properties and methods of the Player in the Game Class, right? Why do I need my game class inside the Player class? Can I, for example, call createPlayer () in the Player class?
I apologize if my explanation was completely confusing.
I think my question comes down to the following; What am I exactly passing as a parameter, and why should I do this in OOP programming every day?