Created
July 28, 2022 14:59
-
-
Save levonlee/5d26ba1df7d742df5d5c87be1fc7730d to your computer and use it in GitHub Desktop.
Explore an option to add capabilities to a class without making it bigger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class A { | |
public static function methodA1(): string { | |
return __METHOD__; | |
} | |
} | |
class B { | |
/** | |
* @var Main | |
*/ | |
private $caller; | |
public function __construct($caller) { | |
$this->caller = $caller; | |
} | |
public function methodB1(): string { | |
$this->caller->counter++; | |
return __METHOD__; | |
} | |
} | |
class Main { | |
public $counter = 0; | |
/** | |
* @var A | |
*/ | |
public static $moduleA; | |
/** | |
* @var B | |
*/ | |
public $moduleB; | |
/** | |
* @return A | |
*/ | |
public static function getStaticModuleA(): A { | |
self::$moduleA = new A(); | |
// although return A; works but phpDoc requires returning an instance | |
return self::$moduleA; | |
} | |
/** | |
* @return B | |
*/ | |
public function getNonStaticModuleB(): B { | |
$this->moduleB = new B($this); | |
return $this->moduleB; | |
} | |
} | |
var_dump(Main::getStaticModuleA()::methodA1() == 'A::methodA1'); | |
$main = new Main(); | |
var_dump($main->getNonStaticModuleB()->methodB1() == 'B::methodB1'); | |
var_dump($main->counter == 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment