The Little Guy Posted March 17, 2012 Share Posted March 17, 2012 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? Quote Link to comment https://forums.phpfreaks.com/topic/259133-multiple-classes-sharing-same-values/ Share on other sites More sharing options...
spfoonnewb Posted March 17, 2012 Share Posted March 17, 2012 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; } } Quote Link to comment https://forums.phpfreaks.com/topic/259133-multiple-classes-sharing-same-values/#findComment-1328469 Share on other sites More sharing options...
ManiacDan Posted March 17, 2012 Share Posted March 17, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/259133-multiple-classes-sharing-same-values/#findComment-1328472 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.