Reputation: 91
I want delete object from arrayObject in php, but in deleteComputer method show this error: "Warning: Illegal offset type", help me pls, Im starting with php :)
i've:
class ControllerList {
private $computers;
function __construct() {
$this->computers= new ArrayObject();
}
public function addComputer($computer) {
$this->computers->append($computer);
}
public function deleteComputer($computerNumber) {
foreach ($this->computers as $value) {
if($value->getNumber() == computerNumber){
unset($this->computers[$value]);
echo 'Delete!!';
} else {
echo 'Don't delete!!';
}
}
}
}
Main file:/
$list = new ControllerList();
$computer1 = new Computer();
$computer1->setNumber(001);
$computer1->setColor("Black");
$computer2 = new Computer();
$computer2->setNumber(002);
$computer2->setColor("White");
$list->addComputer($computer1);
$list->addComputer($computer2);
$list->deleteComputer(001); --> error method
Upvotes: 0
Views: 797
Reputation: 351
As with Barmar's solution, I would address your escaping issue here.
echo 'Don't delete!!';
to
echo "Don't delete!!";
or
echo 'Don\'t delete!!';
Additional information on escaping strings can be found here: Escaping quotation marks in PHP
Upvotes: 0
Reputation: 780889
$value
is an object, not an array index. You need to add the array index to the foreach
loop:
foreach ($this->computers as $i => $value) {
if($value->getNumber() == $computerNumber){
unset($this->computers[$i]);
echo 'Delete!!';
} else {
echo 'Don't delete!!';
}
}
Upvotes: 2