PHP属性初始化,为什么这里报语法错误?
PHP 官网中有对 Properties 的讲解,和你问题相关的内容如下:
They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
类的属性的声明可以接受一个初始值,但是初始值必须是一个常量,就是必须在编译过程中可以求值的,并且求值过程不能依赖于运行期间的信息。
date( 'm/d/y h:i:s' ) 并不是一个常量,无法在编译期间求值,所以不是一个合法的属性的初始值。如果你希望在类初始化的时候就给 $birthday 赋值,那像下面一样写:
Class Test {
public $name = 'blues wayne';
public $birthday;
public function __construct() {
$this->birthday = date( 'Y-m-d' );
}
}
2024-07-18 广告