PHP:如何使一个函数接受一个对象,该对象可以是基于调用或用户输入的不同类


PHP: How to make a function accept a single object which can be of different classes based on the call or user input?

好的,这是我的print_details函数

class Vehicle{
      //constructor goes here 
      public function print_details(//one object as parameter)
      {
            echo "'nName : $this->name";
            echo "'nDescription: $this->desc 'n";
            if(strnatcasecmp(get_class($this),"Car")==0)
            {
               $this->getCarDetails();
            }  
            elseif (strnatcasecmp(get_class($this),"Bus")==0)
            {
               $this->getBusDetails();
            }
      }
}  

我打算只使用一个对象作为参数,它可以是CarBus类。但是它应该根据对象的类调用相应的函数。

这可能吗?如果是,如何?

我建议您使用以下类结构:

abstract class Vehicle {
    protected $name;
    protected $desc;
    abstract public function getDetails();
    //constructor goes here
    public function print_details()
    {
        echo "Name : $this->name", PHP_EOL;
        echo "Description: $this->desc", PHP_EOL;
        foreach ($this->getDetails() as $key => $value) {
            echo "{$key}: {$value}", PHP_EOL;
        }
    }
    public function getName()
    {
        return $this->name;
    }
    public function setName($name)
    {
        $this->name = $name;
    }
    public function getDesc()
    {
        return $this->desc;
    }
    public function setDesc($desc)
    {
        $this->desc = $desc;
    }
}
class Car extends Vehicle {
    protected $type;
    public function getType()
    {
        return $this->type;
    }
    public function setType($type)
    {
        $this->type = $type;
    }
    public function getDetails()
    {
        return [
            'Type' => $this->type
        ];
    }
}
class Bus extends Vehicle {
    protected $numberOfSeats;
    /**
     * @return mixed
     */
    public function getNumberOfSeats()
    {
        return $this->numberOfSeats;
    }
    /**
     * @param mixed $numberOfSeats
     */
    public function setNumberOfSeats($numberOfSeats)
    {
        $this->numberOfSeats = $numberOfSeats;
    }
    public function getDetails()
    {
        return [
            'Number of seats' => $this->numberOfSeats
        ];
    }
}
$car = new Car();
$car->setName('BMW');
$car->setDesc('Car description');
$car->setType('sedan');
$car->print_details();
$car = new Bus();
$car->setName('Mers');
$car->setDesc('Bus description');
$car->setNumberOfSeats(20);
$car->print_details();