且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

隐式类变量声明在php?

更新时间:2022-12-15 11:01:46

这与正常变量声明相同工作:

This works the same as a normal variable declaration would work:

$foo = 'bar'; // Created a new variable

class Foo {
    function __construct() {
        $this->foo = 'bar'; // Created a new variable
    }
}

与其他语言一样,其中成员变量需要被指定为类声明的一部分。可以随时创建PHP类成员。

PHP classes are not quite the same as in other languages, where member variables need to be specified as part of the class declaration. PHP class members can be created at any time.

这样,你应该声明变量 public $ foo = null; 在类声明中,如果它应该是类的永久成员,以清楚表达意图。

Having said that, you should declare the variable like public $foo = null; in the class declaration, if it's supposed to be a permanent member of the class, to clearly express the intent.