Home > database >  How can i make my delete function work in php
How can i make my delete function work in php

Time:11-12

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();
}

CodePudding user response:

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])

CodePudding user response:

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.

  • Related