Jump to content

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)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.