简体   繁体   中英

How can i make my delete function work in php

my code was working but i don't know how to create a delete function i tried my best to search some but it doesn't fit in this code im still learning the basics and i will really appreciate the help, thank you very much in advance

<?php

$straw = [];
$index = 0;

class Fruit {

    private $name;
    private $color;

    public function describe($name, $color) {
        $this->name = $name;
        $this->color = $color;
    }

    public function intro() {
        echo "{$this->name}"."\n";
        echo "{$this->color}"."\n";
    }
}

// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
  
    public function getfruit() {
        echo $this->intro();
    }

    public function assignfruit($name, $color){
        $this->describe($name, $color);
    }

    public function deletePatient($index){
        unset($this->intro[$index]);
    }
}

$strawberry1 = new Strawberry();
$strawberry1->assignfruit("Strawberry", "red");
$straw[$index] = $strawberry1;
$index++;

$strawberry2 = new Strawberry();
$strawberry2->assignfruit("Strawberry", "red");
$straw[$index]= $strawberry2;
$index++;

$strawberry2->deletePatient(1);

foreach ($straw as $star){
    echo $star->getfruit();
}

Seems like you want to delete a fruit?

You store the fruits in an array called $straw . So if you want to delete one, you need to delete it from that array.

Try this:

unset($straw[0]);
foreach ($straw as $star) {
    echo $star->getfruit();
      
}

That should delete the first entry into the array, and therefore your first fruit.

Code that deletes fruit shouldn't be located inside your Strawbery object because Strawbery shouldn't delete itself.

It can be placed in some FruitService class, which could be responsible for creation, and deletion of fruits.

If you just want to delete Strawbery object from array, use

unset ($straw[$index])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM