ArrayAccessインターフェースの例 : PHP

Pocket

前回は、IteratorAggregateインターフェースのサンプルを書いた。今回は、ArrayAccessインターフェースのサンプルを書く。

前回のコードにArrayAccessを追加する。

<?php


class TimeCards implements ArrayAccess, IteratorAggregate
{
    private $timeCards;
    private $rate;
    public function __construct($rate)
    {
        $this->rate = $rate;
        $this->timeCards = [];
    }

    /**
     * @param mixed $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return isset($this->timeCards[$offset]);
    }

    /**
     * @param mixed $offset
     * @return mixed|null
     */
    public function offsetGet($offset)
    {
        return $this->timeCards[$offset] ?? null;
    }

    /**
     * @param mixed $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->timeCards[] = $value;
        } else {
            $this->timeCards[$offset] = $value;
        }
    }

    public function offsetUnset($offset)
    {
        unset($this->timeCards[$offset]);
    }

    public function getIterator()
    {
        return new ArrayIterator($this->timeCards);
    }

    public function calculatePay()
    {
        $hours = array_reduce($this->timeCards, function($carry, $item) {
            return $carry + $item;
        }, 0);
        return $this->rate * $hours;
    }
}

$timeCards = new TimeCards(1250);


$timeCards['mon'] = 8;
$timeCards['tue'] = 8.5;
$timeCards['wed'] = 8.25;
$timeCards['thu'] = 8.25;
$timeCards['fri'] = 8;

foreach($timeCards as $index => $value) {
    echo $index . ': ' . $value . PHP_EOL;
}

$payment = $timeCards->calculatePay();
echo $payment;
mon: 8
tue: 8.5
wed: 8.25
thu: 8.25
fri: 8
51250

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。