php - Instantiating objects for use in static accessors -
background
i have 2 classes, , b, class full of static methods (behat/mink step definitions), using logic methods instance of class b.
what want have class able use methods instance of b, have no constructor.
class { // class needs instance of b, has no constructor const b_instance = new b(); //surely not? } class b { public function __construct() {} public function methodforuseinclassa() {...} }
nuance
right now, have extending b, unit testing purposes, instantiating b better solution.
question
how can facilitate this? there accepted best practice this?
any tips appreciated!
either try extend class extends b {}
, you'll have access methods of b. or try one:
class { //this class needs instance of b, has no constructor private static $instanceofb = null; // singleton returns same object while script running public static function getinstanceofb() { if( self::$instanceofb === null ) { self::$instanceofb = new b(); } return self::$instanceofb; } // returns new instance public static function getnewinstanceofb() { return new b(); } } class b { public function __construct() {} public function methodforuseinclassa() { // } }
you can call this, think extending better option, except need static helper methods.
$b = a::getinstanceofb(); $b->methodforuseinclassa();
Comments
Post a Comment