Home >php教程 >php手册 >php中对静态变量的初始化

php中对静态变量的初始化

WBOY
WBOYOriginal
2016-06-13 11:38:051232browse

php的成员变量可以在声明的同时进行初始化,但是只能用标量进行初始化,例如:

class A {
public $f1 = 'xxxx';
static public $f2 = 100;
}

如果要将变量赋值为对象,那么只能在构造器中进行初始化,例如:

class A {
private $child;
public function __construct() {
$this->child = new B();
}
}

但是php中并没有一个类似java中的静态构造器/静态块的东西,就没有合适的时机对其进行初始化了。对于共有的成员还有办法解决,例如:
class A {
static public $child;
}
A::$child = new B();

对于私有的成员似乎就没有什么干净的方法了,只能这样做:

class A {
static private $child;
static public initialize() {
self::$child = new B();
}
}
A::initialize();
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn