Wednesday, April 18, 2012

What's the best way to cast a custom Class in PHP

I know off the bat some of you will assume Interface or Abstract, but that only handles SOME of the situations. Here's an example where they break.



Assume we have classes that implement the same interface and extend the same base



  class car extends fourwheeler implements ipaygas{       

var tank1;

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

}

class sportcar extends fourwheeler implements ipaygas{

var tank1;
var tank2;

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

}

interface ipaygas{

function payGas($amount);
}


In some situations an interface is all you need as you may only want to execute 'payGas()'. But what do you do when you have conditions to be met.



Example, what if - before paying gas you need to (1) check the car type, (2) use premium gas for the sports car, and (3) fill the second tank of the sports car.



THIS IS WHAT I WANT TO DO BUT CANNOT



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


How can I do this with real type casting? Is it possible in PHP?





No comments:

Post a Comment