How to Cast Objects in PHP

后端 未结 12 1959
轮回少年
轮回少年 2020-11-27 04:24

Ive some classes that share some attributes, and i would like to do something like:

$dog = (Dog) $cat;

is it possible or is there any gener

12条回答
  •  佛祖请我去吃肉
    2020-11-27 04:35

    You do not need casting. Everything is dynamic.

    I have a class Discount.
    I have several classes that extends this class:
    ProductDiscount
    StoreDiscount
    ShippingDiscount
    ...

    Somewhere in the code I have:

    $pd = new ProductDiscount();
    $pd->setDiscount(5, ProductDiscount::PRODUCT_DISCOUNT_PERCENT);
    $pd->setProductId(1);
    
    $this->discounts[] = $pd;
    
    .....
    
    $sd = new StoreDiscount();
    $sd->setDiscount(5, StoreDiscount::STORE_DISCOUNT_PERCENT);
    $sd->setStoreId(1);
    
    $this->discounts[] = $sd;
    

    And somewhere I have:

    foreach ($this->discounts as $discount){
    
        if ($discount->getDiscountType()==Discount::DISCOUNT_TYPE_PRODUCT){
    
            $productDiscount = $discount; // you do not need casting.
            $amount = $productDiscount->getDiscountAmount($this->getItemTotalPrice());
            ...
        }
    
    }// foreach
    

    Where getDiscountAmount is ProductDiscount specific function, and getDiscountType is Discount specific function.

提交回复
热议问题