嗨,这就是我需要做的:
首先我有一门课:
class Product
{
private $name;
private $price;
private $sellingByKg;
public function __construct($name = null, $price = null, $sellingByKg = null)
{
$this->name = $name;
$this->price = $price;
$this->sellingByKg = $sellingByKg;
}
public function getName()
{
return $this->name;
}
public function getPrice()
{
return $this->price;
}
public function getSellingByKg()
{
return $this->sellingByKg;
}
然后我有另一个扩展Products类的类:
class MarketStall extends Product
{
public $products;
public function __construct(
$products= [],
$name = null,
$price = null,
$sellingByKg = null
) {
parent::__construct($name, $price, $products);
$this->products = $products;
}
我需要做的是,属性产品必须只接受一个关联数组,其中数组的键是产品的名称,数组的值将是Product类的对象。
验证它是否是一个assoc数组。(PHP8+(
if (array_is_list($products)) {
throw new Exception("Assoc array expected");
}
但是,如果您使用的是PHP8以下的版本,则可以用function_exists()
函数来封装array_is_list
函数。
if (!function_exists('array_is_list')) {
function array_is_list(array $arr)
{
return $arr === [] || (array_keys($arr) === range(0, count($arr) - 1));
}
}