草庐IT

php - 在 PHP 中转换自定义类的最佳方法是什么

coder 2024-04-29 原文

我马上就知道你们中的一些人会假设接口(interface)或抽象,但这只能处理某些情况。这是它们损坏的示例。

假设我们有实现相同接口(interface)并扩展相同基类的类

  class car extends fourwheeler implements ipaygas{       

    protected $tank1;

    //interface
    public function payGas($amount){}

  }

  class sportscar extends fourwheeler implements ipaygas{

    protected $tank1;
    protected $tank2;

    //interface
    public function payGas($amount){}

  }

  interface ipaygas{

    function payGas($amount);
  }

在某些情况下,您只需要一个接口(interface)即可,因为您可能只想执行“payGas()”。但是当你有条件要满足时你会怎么做。

例如,如果 - 在支付汽油费之前,您需要 (1) 检查车型,(2) 为跑车使用高级汽油,以及 (3) 为跑车的第二个油箱加满油。

这是我想做却做不到的

   function pumpAndPay(iPayGas $car){
     if(gettype($car) == "car"){
       fillTank($car,(car) $car->tank1);
     }else{
       fillTank($car,(sportscar) $car->tank1);
       fillTank($car,(sportscar) $car->tank2);
     }
   }

如何使用真实类型转换来做到这一点?在 PHP 中可以吗?

更新(基于回复): 在我的“真实”案例中……假设我必须检查各种车辆类型,每种车辆都有不同的油漆、车身、内饰、gas_type、cleaner_type、颜色等……

   abstract class AVechicle{}
   abstract class ACar extends AVechicle{}
   abstract class ATruckOrSUV extends AVechicle{}
   abstract class ABike extends AVechicle{}

   class Car extends ACar{}
   class SportsCar extends ACar{}
   class SUV extends ATruckOrSUV{}
   class Truck extends ATruckOrSUV{}
   class Bike extends ABike{}
   class Scooter extends ABike{}

   class GasStation{

     public function cleanVehicle(AVehicle $car){
       //assume we need to check the car type to know
       //what type of cleaner to use and how to clean the car
       //if the car has leather or bucket seats

       //imagine we have to add an extra $2/h for sports cars

       //imagine a truck needs special treatment tires
       //or needs inspection
     }

     public function pumpAndPay(AVehicle $car){
       //need to know vehicle type to get gas type

       //maybe we have a special for scooters only, Green Air campaign etc.
     }

     public function fullService(AVehicle $car){
       //need to know if its a truck to do inspection FIRST

       $this->cleanVehicle($car);
       $this->pumpAndPay($car);

       //bikes get 10% off
       //cars get free carwash
     }

   }

仅靠接口(interface)和抽象就够了……

最佳答案

对你的问题的简短回答,不,你不能将一个对象重新转换为另一个对象。

不过,Dan Lee 的回应很好,接近我的建议。为什么不让 fillTank 成为车辆对象的属性,这样所有扩展车辆类的对象都知道如何填充自己的油箱。像这样:

abstract class Vehicle
{
    protected $tank1;
    protected $tank2;

    // Declaring an abstract function in parent class forces all child class to 
    // implement same class
    abstract public function fillGas() {}
}

class Car extends Vehicle
{
    public function fillGas()
    {
        $this->tank1 = 'full';
    }
}

class SportsCar extends Vehicle
{
    public function fillGas()
    {
        $this->tank1 = 'full';
        $this->tank2 = 'full';
    }
}

class Skateboard extends Vehicle
{
    // Skateboards don't have gastanks, just here to sastify parent abstract definition
    public function fillGas() {}
}

当然,您的 OP 的最大谬误是您假设所有跑车都有两个油箱,而实际上并非如此。只有某些跑车有多个油箱。

另一种方法是查看traits ( available as of PHP 5.4 )。看来您可以在不扩展同一类的对象之间强制执行接口(interface)和实现。

-- 更新--

Update (Based on responses): In my 'real' case... imagine I have to check various Vehicle types, each with different paint, body, interior, gas_type, cleaner_type, color, etc...

您提到的所有这些属性都是车辆属性,而不是 gastation、fillingstation、parkinglot 等属性,因此我会将所有这些属性添加到车辆类中,然后您可以将车辆传递给 GasStation::cleanVehicle( ) 操纵车辆属性的工厂方法。

下面的代码片段只是DEMONSTRATIVE,展示了如何将上述属性附加到车辆类,以及 GasStation 类如何根据类操作车辆属性的车辆。我在 5 分钟内写了以下内容,但很明显,正确处理工厂方法以及是否传递给其他对象等需要更多考虑。考虑以下几点:

abstract class Vehicle
{
    // Setting these to public for demonstration only, otherwise you should set these 
    //  to protected and write public accessors 
    public $paintType;
    public $bodyType;
    public $interior;
}

class Car extends Vehicle
{
}

class Suv extends Vehicle
{
}

class Truck extends Vehicle
{
}

class GasStation
{
    public static function cleanVehicle(Vehicle $vehicle)
    {
        switch (get_class($vehicle)) {

            case 'Car':
                // Car specific cleaning
                break;

            case 'Truck':
                // Truck specific cleaning
                break;

            default:
                throw new Exception(sprintf('Invalid $vehicle: %s', serialize($vehicle)));
        }

        // We've gone through our vehicle specific cleaning, now we can do generic
        if ('Leather' === $vehicle->getInterior()) {
            // Leather specific cleaning
        }

        if ('Sedan' === $vehicle->getBodyType()) {
            // Sedan specific cleaning
        }
    }
 }

$car = new Car();

$car->setPaintType = 'Glossy';
$car->setBodyType = 'Sedan';
$car->setInterior = 'Cloth';

$suv = new Suv();

$suv->setPaintType = 'Glossy';
$suv->setBodyType = 'Crossover';
$suv->setInterior = 'Leather';

$truck = new Truck();

$truck->setPaintType = 'Flat';
$truck->setBodyType = 'ClubCab';
$truck->setInterior = 'Cloth';

$vehicles = array($car, $suv, $truck);

foreach ($vehicles as $vehicle) {
    GasStation::cleanVehicle($vehicle);
}

关于php - 在 PHP 中转换自定义类的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10217428/

有关php - 在 PHP 中转换自定义类的最佳方法是什么的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  3. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  4. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  7. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  8. ruby - 如何使用文字标量样式在 YAML 中转储字符串? - 2

    我有一大串格式化数据(例如JSON),我想使用Psychinruby​​同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解

  9. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  10. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

随机推荐