Just curious.
if I assign self::$session = $reg->get('session');
in a __construct
class, can the variable be used as the class' properties just like $this->session = $reg->get('session');
?
I have no idea how to test this. The only way I could test this is to make my entire framework in ruin by changing them all.
Just tried a bit around what is possible on the PHP shell ( php -a
).
php > class a { public $b; function __construct () { self::$b = 10; } }
php > $o = new a;
PHP Fatal error: Access to undeclared static property: a::$b in php shell code on line 1
php > class a { public static $b; function __construct () { $this->b = 10; } }
php > $o = new a;
php > print $o->b;
10
php > print a::$b;
php > // outputs nothing (is still NULL)
php > class a { public static $b; function __construct () { self::$b = 10; } }
php > $o = new a;
php > print $o->b;
PHP Notice: Undefined property: a::$b in php shell code on line 1
php > // doesn't print a value (basically NULL)
self::...
). No, you cannot switch between static and non-static accesses and writes.
Before I start this, you could test this easily with an online codepad tool as well, but I felt it might be better to actually explain what's going on.
Let's assume you have this class, based on what you have described:
class MyClass
{
private static $session;
public function __construct($reg)
{
self::$session = $reg->get('session');
}
}
The expression self::$session
references a class variable which is shared amongst all instances of MyClass
.
Let's change the class to the following:
class MyClass
{
private $session;
public function __construct($reg)
{
$this->session = $reg->get('session');
}
}
Now, the expression $this->session
references an instance variable, which is not shared with any other instance of MyClass
.
Because of this difference, they can't be used interchangeably and you will have to make a decision based on your functional design.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.