0

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
1
  • computerNumber should be $computerNumber Commented Mar 29, 2017 at 23:49

2 Answers 2

2

$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!!';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.