如何从foreach循环中的对象获取属性值?

时间:2022-05-09 22:30:18

I iterate through an array(using a foreach loop) that contains two 'High Season' objects - the two objects have an id, start date and end date. I get the high season start date via getter and assign it to a variable with intentions of incrementing the month when I loop through the date difference of the high season's start date and end date. When I loop through the date difference, the Booking start date and end date are compared against the variable I have been incrementing by month, and then the variable "containing" the date is incremented by one month.

我遍历一个包含两个“旺季”对象的数组(使用foreach循环) - 这两个对象具有id,开始日期和结束日期。我通过getter得到了旺季的开始日期并将其分配给一个变量,当我循环通过旺季的开始日期和结束日期的日期差异时,意图增加月份。当我遍历日期差异时,将预订开始日期和结束日期与我按月增加的变量进行比较,然后将“包含”日期的变量增加一个月。

Does this variable contain a reference to the array's high season object's start date property? when I dump the high seasons array the start date has changed to the same date as the variable that has been incremented by one month. How do I get the value of the high season start date property and not the reference of the array object's start date?

此变量是否包含对数组的高级对象的开始日期属性的引用?当我转储高季节数组时,开始日期已更改为与已增加一个月的变量相同的日期。如何获取旺季开始日期属性的值而不是数组对象的开始日期的引用?

I am using PHP 5.5.30.

我使用的是PHP 5.5.30。

foreach ($highseasons as $highseason) {
    $HSDate = $highseason->getStartDate();
    $diff = date_diff($highseason->getStartDate(), $highseason->getEndDate());

    $months = (int)$diff->format('%m');
    $SDBool = false;
    $EDBool = false;

    // loop through the date difference
    for ($i = 0; $i <= $months; $i++) {
        var_dump($highseasons);
        $HSMonth = $HSDate->format('m');
        $BookingStartingMonth = $value->getStartDate()->format('m');
        $BookingEndingMonth = $value->getEndDate()->format('m');

        if ($HSMonth == $BookingStartingMonth) {
            $SDBool = true;
        }

        if ($HSMonth == $BookingEndingMonth) {
            $EDBool = true;
        }

        // add one month onto the high season date
        $HSDate->add(new DateInterval('P1M'));
    }
}

1 个解决方案

#1


1  

As the start date is a DateTime object, yes it is a reference and modifying it will change the value of the highseason's start date as well (since they are the same object).

由于开始日期是DateTime对象,因此它是一个引用,修改它也会改变highseason的开始日期的值(因为它们是同一个对象)。

In order to do what you are asking for, you need to clone the DateTime object:

为了满足您的要求,您需要克隆DateTime对象:

$tempDate = clone $HSDate;

and increment the new date object instead.

并改为增加新的日期对象。

#1


1  

As the start date is a DateTime object, yes it is a reference and modifying it will change the value of the highseason's start date as well (since they are the same object).

由于开始日期是DateTime对象,因此它是一个引用,修改它也会改变highseason的开始日期的值(因为它们是同一个对象)。

In order to do what you are asking for, you need to clone the DateTime object:

为了满足您的要求,您需要克隆DateTime对象:

$tempDate = clone $HSDate;

and increment the new date object instead.

并改为增加新的日期对象。