简体   繁体   English

我怎样才能让我的删除功能在 php 中工作

[英]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 .您将水果存储在名为$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.删除水果的代码不应位于您的 Strawbery 对象内,因为 Strawbery 不应删除自身。

It can be placed in some FruitService class, which could be responsible for creation, and deletion of fruits.它可以放在一些 FruitService 类中,该类可以负责创建和删除水果。

If you just want to delete Strawbery object from array, use如果您只想从数组中删除 Strawbery 对象,请使用

unset ($straw[$index])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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