KingIsulgard Posted November 28, 2009 Share Posted November 28, 2009 Is there a way in PHP to protect certain classes to only be created via another class? So you can't access them directly, it should first pass another class before it gets created. So CLASSA->do(); will return an instance of CLASSB but CLASSB() shouldn't work to get an instance. Is something like this possible? I want to create something like packages in java. Link to comment https://forums.phpfreaks.com/topic/183228-php-class-get-by-class/ Share on other sites More sharing options...
Mchl Posted November 28, 2009 Share Posted November 28, 2009 Make CLASSB constructor private. Also create a static method CLASSB::getInstance($CLASSAobject) that will return an instance if $CLASSAobject is implementing the correct interface. (I don't like this solution, but can't think of anything bbetter right now) Link to comment https://forums.phpfreaks.com/topic/183228-php-class-get-by-class/#findComment-967018 Share on other sites More sharing options...
KingIsulgard Posted November 29, 2009 Author Share Posted November 29, 2009 I already made the static function and made the constructors protected, but that didn't work eather. Link to comment https://forums.phpfreaks.com/topic/183228-php-class-get-by-class/#findComment-967444 Share on other sites More sharing options...
MadTechie Posted November 29, 2009 Share Posted November 29, 2009 I'm probably missing thing here but can't you just make class B abstract ie <?php abstract class ClassB{ function __construct(){} function test(){ return "Class B"; } } class ClassA extends ClassB{ function DoIT(){ return $this; } } $A = new ClassA(); $B = $A->DoIT(); echo $B->test(); // returns "Class B" $X = new ClassB(); // return Fatal error: Cannot instantiate abstract class ClassB Link to comment https://forums.phpfreaks.com/topic/183228-php-class-get-by-class/#findComment-967454 Share on other sites More sharing options...
Mchl Posted November 29, 2009 Share Posted November 29, 2009 How about this? <?php interface interfaceA {} class CLASSA { public function doSomething() { return CLASSB::returnInstance($this); } } class CLASSAi implements interfaceA { public function doSomething() { return CLASSB::returnInstance($this); } } class CLASSB { private function __construct() {} public static function returnInstance($obj) { if($obj instanceof interfaceA) { return new CLASSB(); } else { return false; } } } $objA = new CLASSA(); var_dump($objA->doSomething()); //bool(false) $objAi = new CLASSAi(); var_dump($objAi->doSomething()); //object(CLASSB) Link to comment https://forums.phpfreaks.com/topic/183228-php-class-get-by-class/#findComment-967455 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.