PHP:无法在声明中分配属性值 [英] Php: can't assign a property value in declaration

查看:84
本文介绍了PHP:无法在声明中分配属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不理解全局上下文和类上下文之间对变量赋值的不同处理背后的理由:

I do not understand the rationale behind the different treatment of variable assignment between global context and class context:

$var1 = "a" . "b"; # PHP syntax o.k.

class myClass {
    private $var2 = "a" . "b"; # PHP Parse error:  syntax error, unexpected '.', expecting ',' or ';'
}

P.S .:财产的可见性(私有/受保护/公共)不起作用.

P.S.: visibility of property (private/protected/public) doesn't play a role.

推荐答案

这不是类上下文中的变量分配". private $var为该类声明一个属性,并且您还为其指定了默认值.您在这里声明类的结构,这与过程代码中的变量分配不同.类结构由解析器解析,然后由编译器编译,并且该属性的默认值在此 parsing/compilation步骤中建立.编译器不会执行任何程序代码;它只能处理恒定值.

It's not a "variable assignment in class context". private $var declares a property for the class, and you're additionally giving it a default value. You're declaring the structure of the class here, which is not the same as a variable assignment in procedural code. The class structure is parsed by the parser and compiled by the compiler and the default value for the property is established in this parsing/compilation step. The compiler does not execute any procedural code; it can only handle constant values.

因此,您不能使用需要 evaluation 的默认值声明类属性,因为处理类声明的PHP部分(解析器/编译器)确实可以不是评估.

As such, you cannot declare class properties with default values which need evaluation, because the part of PHP that handles the declaration of classes, the parser/compiler, does not evaluate.

这篇关于PHP:无法在声明中分配属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆