【发布时间】:2017-11-21 21:39:00
【问题描述】:
我有一个对象数组 $factories,我正在循环使用 foreach 通过该数组,然后通过对象的数组属性。
$f->inputResources[0]['checked']=2; // this sets the array correctly
foreach($factories as $f){
foreach($f->inputResources as $i){
echo $i['resource']." ".$i['amount']." ".$i['checked']."<br>"; // these values are correctly retrieved from the object
$i['checked']=5; // but this doesn't set the object's array although it sets the $i['checked'] that is echoed down correctly
echo $i['resource']." ".$i['amount']." ".$i['checked']."<br>";//looks like it was set correctly
echo print_r($f-> inputResources); //here we figure out it wasn't set correctly to 5 and it's still the old value
}
}
为什么$i['checked']=5; 没有正确设置对象的关联数组属性,而回显$i['checked'] 从对象中检索到正确的属性值?
这是课程代码:
class factory
{
var $id;
var $name;
var $player; //the owner
var $planet;
var $type;
var $govOwned; //0 player owned 1 government owned
var $output; //0 factory storage 1 market
var $price; //price of auto market ouput
var $resource;//resource which factory is producing
var $workers;
var $wage;
var $money;
var $starveIndex;
var $inputResources;
var $reservedResources;
var $storage;
public function __construct($data)
{
$this->id = $data['id'];
$this->name = $data['name'];
$this->player = $data['player_id'];
$this->planet = $data['planet_id'];
$this->type = $data['factory_type'];
$this->govOwned = $data['gov_owned'];
$this->output = $data['output_where'];
$this->price = $data['price'];
$this->resource = $data['resource_id'];
$this->workers = $data['workers'];
$this->wage = $data['worker_wage'];
$this->starveIndex = $data['workers_starve'];
$this->inputResources[] = array('resource' => $data['resource_needed'], 'amount' => $data['amount'], 'checked' => 0);
// etc.
}
public function addInputResource($resource, $amount)
{
$this->inputResources[] = array('resource' => $resource, 'amount' => $amount, 'checked' => 0);
}
public function addStorage($resource, $amount)
{
$this->storage[] = array('resource' => $resource, 'amount' => $amount);
}
}
PS:是的,我可能可以通过 setter 方法解决这个问题......我仍然很好奇为什么这不起作用。还有php7
【问题讨论】: