类 - 变量声明

akh*_*.cs 19 php oop

当声明PHP类变量时,我们无法执行任何表达式,例如:

class A
{
    $a = 10 + 5;
}
Run Code Online (Sandbox Code Playgroud)

只有我们可以提供常量,例如:

class A
{
   $a = 100;
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以知道为什么会这样吗?

Sha*_*ran 28

这是因为表达式不允许作为字段默认值.使用构造函数来初始化变量.

我建议你这样做..

class A
{
    public $a;

    function __construct()
    {
        return $this->a = 10 + 5;
    }
}

$a1 = new A;
echo $a1->a; //"prints" 15
Run Code Online (Sandbox Code Playgroud)

  • 如果成员是静态的并且不需要实例化该类,该怎么办? (2认同)
  • 好点@bigp.一个(另一个)理由为什么PHP似乎有点糟糕.顺便说一下,解决方法是使用静态函数...例如public static function getA(){return 10 + 5} (2认同)

小智 16

您不能使用语句或函数,只能使用标量值.这是因为类变量是在编译时启动的(在运行时之前).应该使用类构造函数来启动带语句/函数的属性.