Initialization of static variables in php_PHP tutorial

WBOY
Release: 2016-07-21 14:55:39
Original
857 people have browsed it

PHP member variables can be initialized at the same time as they are declared, but they can only be initialized with scalars, for example:

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

If you want to assign a variable to an object, it can only be initialized in the constructor, for example:

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

But there is nothing similar to the static constructor/static block in Java in PHP, so there is no appropriate time to initialize it. There are also solutions for shared members, for example:
class A {
class A {
static public $child;
}
A::$child = new B();
static public $child;

}

A::$child = new B();

There seems to be no clean way for private members, the only way is to do this:

class A {
static private $child;
static public initialize() {
self::$child = new B();
}
}
A::initialize();
class A { static private $child;

static public initialize() {

self::$child = new B(); } A::initialize();
http://www.bkjia.com/PHPjc/364373.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/364373.html
TechArticle
PHP member variables can be initialized at the same time as they are declared, but they can only be initialized with scalars, for example: class A { public $f1 = 'xxxx'; static public $f2 = 100; } If you want to change...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!