目前我正在使用PHP中的一個簡單的OOP腳本,它需要比較數組的ID和DATE並按正確的順序對它們進行排序。如何正確構建PHP中的類中的數組?
我想知道爲什麼我的第一個類的構造函數沒有正確傳遞$ elements數組。
我得到的錯誤:
Notice: Undefined variable: elements in /Applications/XAMPP/xamppfiles/htdocs/strategy-pattern-.php on line 58
Catchable fatal error: Argument 1 passed to ObjectCollection::__construct() must be of the type array, null given, called in ... on line 58 and defined in ... on line 12
代碼:
<?php
class ObjectCollection
{
var $elements = array(
array('id' => 2, 'date' => '2017-01-01',),
array('id' => 1, 'date' => '2017-02-01'));
var $comparator;
function __construct(array $elements)
{
$this->elements = $elements;
}
function sort()
{
if (!$this->comparator) {
throw new \LogicException('Comparator is not set');
}
uasort($this->elements, [$this->comparator, 'compare']);
return $this->elements;
}
function setComparator(ComparatorInterface $comparator)
{
$this->comparator = $comparator;
}
}
interface ComparatorInterface
{
function compare($a, $b);
}
class DateComparator implements ComparatorInterface
{
function compare($a, $b)
{
$aDate = new \DateTime($a['date']);
$bDate = new \DateTime($b['date']);
return $aDate <> $bDate;
}
}
class IdComparator implements ComparatorInterface
{
function compare($a, $b)
{
return $a['id'] <> $b['id'];
}
}
$collection = new ObjectCollection($elements);
$collection->setComparator(new IdComparator());
$collection->sort();
echo "Sorted by ID:\n <br>";
print_r($collection->elements);
$collection->setComparator(new DateComparator());
$collection->sort();
echo "<br>Sorted by date:\n <br>";
print_r($collection->elements);
?>
我知道有可能只是一個新手的錯誤的地方,但我是我做的真的很好奇自己做錯了什麼,哈哈。
在此先感謝! :)
嘛'var'一直沒有在相當一段時間內使用的屬性定義。你使用什麼手冊? PHP4 – RiggsFolly