Reputation: 5936
I have a PHP class method which is using a static function from with a another class. How do i enable that static function to modify variables within the calling class.. Example as follows:
PARENT:
class sys_core
{
public $test = 'no';
// --------------------
public function __construct()
{
}
// --------------------
public function init()
{
sys_loader::load_config('123');
print $this->test;
}
// --------------------
// --------------------
// --------------------
// --------------------
// --------------------
} // END Class
STATIC CLASS
class sys_loader
{
private $registry = array();
// --------------------
public static function load_config($file)
{
$this->test = 'yes';
}
// --------------------
// --------------------
// --------------------
// --------------------
} // END Class
ERROR:
Fatal error: Using $this when not in object context
Upvotes: 0
Views: 641
Reputation: 244
As I see it, sys_loader can modify sys_core's $test 3 ways:
1) sys_loader is passed a reference to sys_core->test,
2) sys_loader returns a new value for it or
3) equip sys_core with a setter for $test and pass sys_loader a reference to sys_core.
With that reference, sys_loader can access whatever variables and functions sys_core allows.
Here are the bits I changed/added to make #3 work:
Example use:
$sc = new sys_core();
$sc->setConfigFile('123');
$sc->init();
Output:
123yes
class sys_core
// new
private $configFile = null;
// new
function getConfigFile() {
return $this->configFile;
}
// new
function setConfigFile($value) {
$this->configFile = $value;
}
// new
function setTest($value) {
$this->test = $value;
}
public function init()
{
// sys_loader::load_config('123');
sys_loader::load_config($this);
print $this->test;
}
class sys_loader
// public static function load_config($file)
public static function load_config($caller)
{
// $this->test = 'yes';
$caller->setTest('yes');
// new, example
$config = $caller->getConfigFile();
// new, example
echo $config;
}
Upvotes: 2
Reputation: 1778
If it helps, you can pass a reference to your sys_core instance as a parameter to the sys_loader::load_config method:
class sys_core
{...
public function init()
{
sys_loader::load_config('123', $this);
print $this->test;
}
...
}
class sys_loader
{
...
// --------------------
public static function load_config($file, $core)
{
$core->test = 'yes';
}
...
}
Upvotes: 1
Reputation: 5385
You can't. By definition, static
means not tied to any object. (What are you trying to accomplish here?)
Static methods are per class, they can take in parameters and modify static variables. Figure out what you need, draw a diagram, and implement it.
Upvotes: 0
Reputation:
You can access any public member outside of that class, private members can only be accessed by the class itself, and protected members can be accessed by sub-classes.
self
is used for static members...one per class.
this
is used for non-static members...one per instance.
Upvotes: 0