Passing an entire class as a parameter inside another class

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?

+6
source share
3 answers

It is called the hinting type , and it does not pass the entire class as a parameter, and rint hints at Class Player about the type of the first parameter

PHP 5 introduces type hints. Functions can now force objects to be objects (by specifying the class name in the function prototype), interfaces, arrays (starting with PHP 5.1) or called (starting with PHP 5.4). However, if NULL is used as the default parameter value, it will be resolved as an argument for any subsequent call.

(extracted from php manual)

Does this mean that the entire class is available in the Player class by reference?

Not the whole class, but you can access the instance of the class that you pass as a parameter

+4
source

The method expects to receive an object that is an instance of Game of something else, and it will fail.

You only pass the Game instance here: New Player($this, $name); The $this refers to the instance of the object you are in.

And the last ... I (and no one else in this regard) knows why the author did this because he does not use the Game instance after its transfer.

Why do you need to pass an instance of a class?
Imagine a class that accepts users as input and, by some logic, does something with them. (There are no comments in the code, as the function name and class name should be clear)

 class User{ protected $name,$emp_type,$emp_id; protected $department; public function __construct($name,$emp_type,$emp_id){ $this->name = $name; $this->emp_type = $emp_type; $this->emp_id = $emp_id; } public function getEmpType(){ return $this->emp_type; } public function setDep($dep){ $this->department = $dep; } } class UserHub{ public function putUserInRightDepartment(User $MyUser){ switch($MyUser->getEmpType()){ case('tech'): $MyUser->setDep('tech control'); break; case('recept'): $MyUser->setDep('clercks'); break; default: $MyUser->setDep('waiting HR'); break; } } } $many_users = array( 0=>new User('bobo','tech',2847), 1=>new User('baba','recept',4443), many more } $Hub = new UserHub; foreach($many_users as $AUser){ $Hub->putUserInRightDepartment($AUser); } 
+3
source
 /** * Game class. */ class Game implements Countable { /** * Collect players here. * * @var array */ private $players = array(); /** * Signal Game start. * */ public function __construct(){ echo 'Game Started.<br />'; } /** * Allow count($this) to work on the Game object. * * @return integer */ public function Count(){ return count($this->players); } /** * Create a player named $name. * $name must be a non-empty trimmed string. * * @param string $name * @return Player */ public function CreatePlayer($name){ // Validate here too, to prevent creation if $name is not valid if(!is_string($name) or !strlen($name = trim($name))){ trigger_error('$name must be a non-empty trimmed string.', E_USER_WARNING); return false; } // Number $name is also not valid if(is_numeric($name)){ trigger_error('$name must not be a number.', E_USER_WARNING); return false; } // Check if player already exists by $name (and return it, why create a new one?) if(isset($this->players[$name])){ trigger_error("Player named '{$Name}' already exists.", E_USER_NOTICE); return $this->players[$name]; } // Try to create... this should not except but it educational try { return $this->players[$name] = new Player($this, $name); } catch(Exception $Exception){ // Signal exception trigger_error($Exception->getMessage(), E_USER_WARNING); } // Return explicit null here to show things went awry return null; } /** * List Players in this game. * * @return array */ public function GetPlayers(){ return $this->players; } /** * List Players in this game. * * @return array */ public function GetPlayerNames(){ return array_keys($this->players); } } // class Game; /** * Player class. */ class Player{ /** * Stores the Player name. * * @var string */ private $name = null; /** * Stores the related Game object. * This allows players to point to Games. * And Games can point to Players using the Game->players array(). * * @var Game */ private $game = null; /** * Instantiate a Player assigned to a Game bearing a $name. * $game argument is type-hinted and PHP makes sure, at compile time, that you provide a proper object. * This is compile time argument validation, compared to run-time validations I do in the code. * * @param Game $game * @param string $name * @return Player */ public function __construct(Game $game, $name){ // Prevent object creation in case $name is not a string or is empty if(!is_string($name) or !strlen($name = trim($name))){ throw new InvalidArgumentException('$name must be a non-empty trimmed string.'); } // Prevent object creation in case $name is a number if(is_numeric($name)){ throw new InvalidArgumentException('$name must not be a number.'); } // Attach internal variables that store the name and Game $this->name = $name; $this->game = $game; // Signal success echo "Player '{$this->name}' was created.<br />"; } /** * Allow strval($this) to return the Player name. * * @return string */ public function __toString(){ return $this->name; } /** * Reference back to Game. * * @return Game */ public function GetGame(){ return $this->game; } /** * Allow easy access to private variable $name. * * @return string */ public function GetName(){ return $this->name; } } // class Player; // Testing (follow main comment to understand this) $game = new Game(); $player1 = $game->CreatePlayer('player 1'); $player2 = $game->CreatePlayer('player 2'); var_dump(count($game)); // number of players var_dump($game->GetPlayerNames()); // names of players 

I rewrote your code for the better and added some missing variables that made this code pointless:

  • In the player class, you do not store the game.
  • In the game class, you support only one player.
  • No error checking ... anywhere.

All these pluses are fixed:

  • Exceptions added (to prevent creating objects)
  • Try{} catch(...){} Handling exceptions that any OOP developer should know
  • Implemented counting interface allowing players to count ($ game)
  • A few more tricks that will give you a good read.

Follow the comments and I hope that your code will become more understandable after reading it.

+2
source

All Articles