I'm new to PHP and I'm not really familiar with classes, my question is how can I get the value of $quantity and pass it to public array which is within a class? My expected array output would be Bag => 10.
Here's my code:
$quantity = 10;
class QuantityLeft{
public array $inventory = [
'Bag' => [$quantity value here]
];
}
CodePudding user response:
Option 1: provide the value through class constructor.
Option 2: Write a setter method and call it on the object
Below example implements both. The member variable should be protected against direct modification, and the setter makes validation of the input parameter to avoid illegal values.
class QuantityLeft {
protected $inventory = [];
public function __construct($quantity) {
$this->setQuantity($quantity);
}
public function setQuantity($quantity) {
if ($quantity < 0) {
throw new OutOfBoundsException('Quantity must be greater or equal 0');
}
$this->inventory['Bag'] = $quantity;
}
}
Usage:
$obj = new QuantityLeft(50);
or
$obj = new QuantityLeft(0);
$obj->setQuantity(50);
CodePudding user response:
try
global $quantity =10
and than:
class QuantityLeft{
public array $inventory = [
'Bag' => global $quantity
];
}