Page 1 of 1

Accessing game methods and properties within class

Posted: 13 November 2021, 13:34
by Woodruff
Hi everybody :)

I am trying to code cleaner by creating dedicated php classes (in separate files) to manage card behaviour.
All these class inherit from a base class that I would call MyClass for this example.

But within these class method, I would need to access some game methods and properties (from mygame.game.php) such as:
  • self::loadPlayerBasicInfos
  • $this->cards (deck component)
I currently pass the object representing the game (defined in mygame.game.php) as a static property of MyClass, in the game constructor.

But is that the right way to do this?
Will that referencing work at any time in the game? (player action, game state action and arguments, zombie turn...).

Code: Select all

// In myclass.php

abstract class MyClass {
	public static MyGame $game; // This will store the reference of the game object
	
	public doSomeStuff() {
		$card_in_db = self::$game->cards->getCard($id);
		$players = self::$game->loadPlayerBasicInfos();
		
		[...]

Code: Select all

// In mygame.game.php

class MyGame extends Table {
	function __construct() {
        	parent::__construct();
        	
        	// Pass a reference to the game object to MyClass
        	MyClass::$game = $this;
	
		[...]
Thanks for your insights!

Take care,
Wood

Re: Accessing game methods and properties within class

Posted: 13 November 2021, 13:58
by thoun
You can do that (I pass the game as constructor parameter, but the result is the same)

Re: Accessing game methods and properties within class

Posted: 13 November 2021, 14:48
by Tisaac
The game is only instanciated once, so i use it as a singleton instead of passing it around.

Re: Accessing game methods and properties within class

Posted: 13 November 2021, 17:04
by RicardoRix

Code: Select all

class MyClass extends APP_GameClass {	
	function __construct($game) 
	{
		$this->game = $game;
		self::getCollectionFromDB( "SELECT player_id id, player_name name, player_score score FROM player" );
	}
You can inherit from APP_GameClass, this way you can at least get the static functions like DbQuery and the like directly, otherwise yes, I pass the game instance.
Tisaac wrote: 13 November 2021, 14:48 The game is only instanciated once, so i use it as a singleton instead of passing it around.
You may need you elaborate, I don't understand.