返回之前PHP类字段发生了变化

时间:2017-02-11 06:07:49

标签: php class

我遇到了一个PHP类字段的问题,它不想使用我的setter方法设置。在setter方法中,一切似乎都很好,一旦方法完成,就像数据消失一样。

这个类有其他的setter和getter方法,但它们看起来很好。仔细查看代码,这一切似乎都是一样的。

private $volunteerType // declare class field

// Function to call class field data
public function getVolunteerType()
{
    // Where my issue currently is... 
    // $this->volunteerType seems to be blank.
    // can't figure out why
    return $this->volunteerType;
}

// Method to set class field data
public function setVolunteerType($inVolunteerType)
{
        $this->volunteerType = $this->valVolunteerType($inVolunteerType);
        // If I do a 
        // die($this->volunteerType);
        // I get the expected result.
        // e.g. 1,2,3,4,5
}

// Method to validate data before it is set in the setter
// Takes in an array of integers
private function valVolunteerType($vol_type)
{
        $validVolunteerType = "";
    foreach($vol_type as $vType)
    {
        $validVolunteerType .= $vType.",";
    }
    $validVolunteerType = rtrim($validVolunteerType, ",");

    return $validVolunteerType;
}

任何人都可以确定我做错了吗?

1 个答案:

答案 0 :(得分:0)

完成每个部分的紧密工作。有一部分代码将一个mysql表中的字符串放入这个应该是数组的类中。

解决方案是对类的验证器部分进行额外检查,以检查它是否正在获取数组。最后,我的验证器看起来像

    private function valVolunteerType($vol_type)
{
    if(!is_array($vol_type))
    {
        $vol_type = explode(",", $vol_type);
    }

    $validVolunteerType = "";
    foreach($vol_type as $vType)
    {
        $validVolunteerType .= $vType.",";
    }
    $validVolunteerType = rtrim($validVolunteerType, ",");

    return $validVolunteerType;
}