Jump to content

Multiple classes sharing same values


The Little Guy

Recommended Posts

Sorry, but I forget how to do this, mostly because I don't do it often.

 

To keep things simple lets say I have 3 classes: Main, A, B

 

class Main{
public $classA, $classB;
public $shared;
public function init(){
	// Do some stuff
	return $this;
}
}

class A{
public function aMethod(){
	$me = $this->shared; // Same value as from B::bMethod()
	// Do some stuff
	return $this;
}
}

class B{
public function bMethod(){
	$me = $this->shared; // Same value as from A::aMethod()
	// Do some stuff
	return $this;
}
}

 

$main = new Main();
$main->classA->aMethod();
$main->classB->bMethod();

 

I really want to be able to call the main class, then tell it what subclass to use and be able to use $this->shared in any class and it will be the same. If changed in any class the other classes should see the change as well. Does that make sense?

Link to comment
Share on other sites

You can declare the variable static. There several other ways this can be done, however to answer your question in the simplest form, see below:

 

class Main {
public $classA, $classB;
public static $shared;
public function init(){
	// Do some stuff
	return $this;
}
}

class A {
public function aMethod(){
	$me = Main::$shared; // Same value as from B::bMethod()
	// Do some stuff
	return $this;
}
}

Link to comment
Share on other sites

You can't do what you're trying to do, you must instantiate the LOWEST classes in order to use their functions. 

 

You could make a __call function in the parent class which attempts to call the functionality of the child classes dynamically, but all child functions would have to be static, not dynamic.

 

If you wish classA and classB to share functionality, you can put that functionality on classMain.  if you want them to share actual values, you'll need to make classMain a static or singleton class (NOT the parent) and make it a variable on classA and classB.

Link to comment
Share on other sites

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.