[英]Accessing object property with variable
I have an object full of arrays, I am able to change an element in an array with this code 我有一个充满数组的对象,我可以使用此代码更改数组中的元素
$i = 0;
$object->property[$i] = "some value";
however the following code does not change the value and returns no errors. 但是,以下代码不会更改该值并且不会返回任何错误。
$i = 0;
$propertyname = "property";
$object->$propertyname[$i] = "some value";
Try: 尝试:
$i = 0;
$propertyname = "property";
$object->{$propertyname}[$i] = "some value";
In order to set a property you should use functions. 要设置属性,您应该使用函数。 This prevents to set properties to invalid values.
这可以防止将属性设置为无效值。 What you want to achieve can be done by a workaround:
您想要实现的目标可以通过一种解决方法来完成:
public function setPoperty($propName,$Value)
{
switch($propName)
{
case ('firstName'):
$this->firstName=$Value;
break;
case ('UserMode'):
if ($Value>0) //prevent from setting to an undesired value
{ $this->UserMode=$Value}
break;
}
}
This is just written from scratch. 这只是从头开始编写的。 But you should get the idea.
但你应该明白这个想法。
Seems like your trying to edit data encapsulated in object by procedural style 看起来像是试图通过程序样式编辑封装在对象中的数据
E: try E:试试
$object->$propertyname[$otherprop['name']$i]; $对象 - > $ PROPERTYNAME [$ otherprop [ '名称'] $ I];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.