Reputation: 43
I'm trying call class method inside another class.
<?php
class A {
public static $instant = null;
public static $myvariable = false;
private function __construct() {}
public static function initial() {
if (static::$instant === null) {
$self = __CLASS__;
static::$instant = new $self;
}
return static::$instant; // A instance
}
}
class B {
private $a;
function __construct($a_instance) {
$this->a = $a_instance;
}
public function b_handle() {
// should be:
$this->a::$myvariable = true;
// but:
// Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
// try with:
// $this->a->myvariable = true;
// but:
// Strict Standards: Accessing static property A::$myvariable as non static
}
}
// in file.php
$b = new B(A::initial());
$b->b_handle();
var_dump(A::$myvariable);
for now, my alternative is:
<?php
class A {
public function set_static($var,$val) {
static::$$var = $val;
}
}
so:
$this->a->set_static('myvariable',true);
what should I do ? what is happen ? am I wrong ?
why I cannot set myvariable as static variable direcly from B class ?
sorry for bad english.
Upvotes: 1
Views: 1291
Reputation: 54841
Refer to the manual: http://php.net/manual/en/language.oop5.static.php
A property declared as static cannot be accessed with an instantiated class object (though a static method can).
So, you cannot in anyway set static
property from class instance.
As an option you can add some setter, which set your static variable:
public function setMyVar($value) {
static::$myvariable = $value;
}
$this->a->setMyVar(true);
Upvotes: 2
Reputation: 16963
Your call,
$this->a::$myvariable = true;
The PHP manual says,
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
This is why you are unable to assign static property through an object.
Simply do this:
A::$myvariable = true;
Here's the reference:
Upvotes: 1