0

正如http://docs.phalconphp.com/en/latest/reference/models.html#understanding-records-to-objects所说,一旦对象加载到内存中,您就可以对其进行编辑。

    $settingCategories = SettingCategory::find();
    foreach($settingCategories as $settingCategory){
        if($settingCategory->type == "2"){
            $settingCategory->type = "asd";
            $settingCategory->intersection = "asd";
        }else{
            $settingCategory->type = "blaa";
            $settingCategory->intersection = "blaa";
        }
        $settingCategory->type = "test";
    }
    $this->view->setVar("settingCategories",$settingCategories);

当我用 volt 循环遍历它时,type 仍然是它的默认值:

{% for settingCategory in settingCategories %}
<div class="tab-content">
    <h4>{{ settingCategory.name }}</h4> 
    <h4>{{ settingCategory.type }}</h4> --> still (int) integer!?
    <h4>{{ settingCategory.intersection }}</h4> --> undefined!?
</div>
{% endfor %}
4

1 回答 1

1

When you are modifying a variable inside a foreach, you are modifying a "temporary variable". What it means is that since it is only a copy of the real variable, when you change it, the real value inside the array isn't changed. Now, on to what you could do to solve this:

Setters/Getters

I personally prefer this one. If what you want to do is data transformation (I.E. you change the value of a field from one thing to another, and you want to use the new value in your code everywhere), I would use setters and getters. Here is an example:

// This is inside your model
protected $type;

public function getType()
{
    if ($this->type === 2) {
        return "asd";
    } else {
        return $this->type;
    }
}

public function setType($type)
{
    if ($type === 2) {
        $this->type = "asd";
    } else {
        $this->type = 1; // or $type, or anything really :)
    }
}

Of course, in your code, you'll have to change $category->type to $category->getType() and $category->setType($type), based on whether you are reading the value or assigning something to it.

The Quick and Dirty Way

Well, if your use case is different, you can use your current code block with a simple modification. Change your foreach to foreach($settingCategories as &$settingCategory). The ampersand makes the variable be passed into the block as a reference (I.E. it is not a copy like your current case). That means changing it will change the real value.

于 2014-05-12T07:05:17.947 回答