Jump to content

PHP Class get by class


KingIsulgard

Recommended Posts

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

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)

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

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)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.