Passing an entire Class as a parameter within another Class

methods, oop, php

Solution

It's called type hinting and he's not passing the entire class as a parameter but ratter hinting the Class Player about the type of the first parameter

PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

(Extracted from php manual)

Does this mean that the entire class is accessible within the Player class by reference?

Not the entire class, but you can access the an instance of the class you are passing as a parameter

Problem

So far I feel like I've understood the concept and the advantages of OOP programming, and I've not really had any difficulties with understanding how to work with classes in PHP. However, this has left me just a little confused. I think I may understand it, but I'm still uncertain. I've been following a set of video tutorials (not sure on the rules on linking to outside resources, but I found them on youtube), and they're pretty self explanatory. Except, frustratingly, when the tutor decided to pass one class as a parameter within another class. At least I think that's what's 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'm instantiating an object of the Game class and calling its method; ``` $game = new Game(); $game-> createPlayer('new player'); ``` Rather frustratingly, the tutor doesn't really explain why he has done this, and hasn't displayed, as far as I can see, any calls in the code that would justify it. Is the magic method constructor in Player passing in the Game class as a reference? Does this mean that the entire class is accessible within the Player class by reference? When referencing $this without pointing to any particular method or property, are you referencing the entire class? If this is what is happening, then why would I want to do it? If I've created a Player inside my Game Class, then surely I can just access my Player Properties and Methods within the Game Class, right? Why would I want my Game Class inside my Player class as well? Could I then, for example, call createPlayer() within the Player class? I apologise if my explanation has been at all confusing. I guess my question boils down to; what is it that I'm passing as a parameter exactly, and why would I want to do it in every day OOP programming?

Original source