将数组强制转换为对象允许使用无效的属性名


Casting an array to an object allows invalid property names?

我可能遇到了一个"wtf PHP?"的时刻。

根据PHP文档[Class member variables] are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration.

我认为这意味着属性必须遵守与变量相同的命名约定。也就是说,它不能以整数开头。下面的代码确实会导致解析错误:

class Foo {
    public $1st_property;
}

文档还说明了何时将数组转换为对象:Arrays convert to an object with properties named by keys, and corresponding values.

所以我试了

$a['1st_key'] = "Hello, World!";
$o = (object)$a;
print_r($o);

1st_key确实是一个属性

<>之前stdClass对象([1st_key] =>你好,世界!)之前

点是:属性名以一个数字开头,这不是一个有效的变量名(当然,我们可以使用$o->{'1st_key'}访问该属性)。但是,为什么当数组被强制转换为对象时,无效的变量名可以成为属性名呢?

这是由cast完成的。从技术上讲,这些名称不是无效的。

你需要改变如何写(定义)这些名字。如果你写:

$1

这是一个无效的标签。但是如果你写

${1}

这个标签不是无效的。

这个问题可能对你来说也很有趣:PHP中的数组到对象和对象到数组-有趣的行为

您是对的-不可能创建一个无效的属性,如:

class Foo {
    public $1st_property;
}

但是你可以这样做:

class Foo {
    function __construct() {
        $this->{'1st_property'} = 'default value';
    }
    function get1st_property() {
        return $this->{'1st_property'};
    }
    function set1st_property($value) {
        $this->{'1st_property'} = $value;
    }
}