如何访问名称无效的属性?
问题描述:
我要向将要通过第三方API发送的stdClass对象添加数据,因此我给这个对象的元素的名称实际上是由该外部服务定义的。
I'm adding data to a stdClass object that is going to be sent through a 3rd party API and so the names I am giving to the elements of this object are actually being defined by that external service.
$insertArray = array();
$insertArray[0] = new stdclass();
$insertArray[0]->Name = $name;
$insertArray[0]->PhoneNumber = $phone;
这一切都在奇妙地工作,直到我碰到一个属性无效的名称:
This was all working wonderfully until I came across a property with an invalid name:
$insertArray[0]->First.Name = $firstname;
所以这不是有效的PHP语法,
So that isn't valid PHP syntax, so is there a way around this?
答
感谢评论(@AbraCadaver),复杂(curly)语法是去无效变量或属性名称的方法:
Thanks to the comments (@AbraCadaver), Complex (curly) syntax is the way to go for invalid variables or property names:
$insertArray[0]->{"First.Name"} = $firstname;