Type cast in PHP: doing the trick beyond the language

Following my last two posts (in portuguese, here and here) about class juggling in PHP I started getting some google hits on “cast class in PHP”.

A couple of days after I just have to duh! myself in the head a couple of times for whining about it and not thinking around the problem: I found a really simple, quick and dirty solution.

First things first, if want to know how to convert integers to booleans and other primitive juggling, go read the excelent manual. You will even find some fine examples on how to convert an object into another class, quite interesting stuff if you’re into the loose and weak PHP way (no pun intended).

So moving on. I’ve been dreaming about class cast (not conversions) but it ain’t possible in PHP. I’d love to have it in place because it would really help those programmers that use doc-blocks and smart auto-doc IDE’s autocompleting. It would also allow a more elegant and cleaner style, namely by going more EAFP and less LBYL.

The solution

So you can’t write (Whatever)$obj->method() in PHP right?

Right! But what about to_Whatever($obj)->method() would it work?

Yep! By wrapping an object in a transparent function call you can:

  • tell the IDE what class you are dealing with, and he’ll tell you back the members on Ctrl+Space
  • throw a catchable error if you pass an incompatible class


/**
 * cast to whatever
 *
 * @param Whatever $obj
 *
 * @return Whatever
 */
function to_whatever(Whatever $obj)
{
  return $obj;
}

So whenever you have an object that the IDE is not aware of it’s class (example: it was returned by some generic function, like your get() method in that handy Registry class you keep asking for things) but you know which class, superclass or interface it should be… just throw it at the cast function!

Complete solution

So, even better, why not create a “static” class that does all the needed casts?



/**
 * "static" class performs all kinds of "casts"
 */
class Cast
{
  /**
   * cast to Db
   *
   * @param Db $obj
   *
   * @return Db
   */
  public static function Db(Db $obj)
  {
    return $obj;
  }

  ...more cast methods...

}

The function above accepts instances of Db or any Db subclass. It does not “cast” to any particular subclass, remember that’s not the point. That would be (as mentioned previously) destroying the benefits of polymorphism. But it does validate that the object is of the right type. And it also puts it back into context!

Let’s se how to use it:



// fetch db from registry
$db = Registry->get('dbconnection');

try
{
  // cast
  $db = Cast::Db($db)
  // use it
  $db->query( ... );
}
catch (Exception $e)
{
  ...
}

So, now your IDE knows that $db should be an instance of Db, regardless of begin DbMysql, DbMysqli or any other subclass of Db. It will show you, connect(), query(), etc.. when you ask for autocomplete.

Also, because your Registry class could be somehow mistaken, these code will validate that you got a valid Db instance from Registry::get(), instead of something totally absurd like a Widget or XML data.

Catchable fatal error: Argument 1 passed to Cast::Db() must be an instance of Db, instance of Whatever given

Beware that wrapping everything in 1 single try {} catch {} you will also catch any exception thrown in the query() method. You should test the exception type (you should throw your own custom exceptions inside of these methods anyway) or wrap the cast call in a single try {} catch {} block.

So that’s it! I know it’s not that elegant, and it does require you to implement a function for every casts you are using in a certain application or framework. Which is not that bad since it helps you track the mess you are into. Perfect would be to create on Cast class per Package, but namespaces are also not available (whinnnnner!)…

Hope you liked the idea and wish it makes your life easier. It’s already working for me.

Leave a Reply







Close
E-mail It
tramadol mechanism wellbutrin pravachol zovirax cialis viagra australia supply buy cheap tramadol o avandia and glucophage tetracyclines mechanism of action generic drugs for lexapro levitra vs cialis vs viagra sildenafil citrate us overnight delivery celexa vs prozac us licensed pharmacies carisoprodol by chicos phentermine 37.5 without precrition different mg of atenolol liquid tadalafil ingestion doses of lexapro alcohol falce positive for fioricet synthroid medication long term use cervical radiculopathy prednisone diclofenac interactions with xanax prozac dailey strength wellbutrin 200 sr maximum prescribed daily does of ultram clomiphene vs tamoxifen as pct dangers of prednisone in dogs canines meridia industrial members corporation email contacts buspar or xanax inventor of lorazepam wyeth soma inc when is xanax prescribed carisoprodol vs methocarbamol workign around sexual side effectson lexapro singulair and acid reflux lexapro positive side effects saturday tramadol delivery medicine cause tendinitis phentermine xanax withdrawls matt lauer as the amazons viagra t pallidum treponema doxycycline tetracycline kentucky weight lose adipex phentermine xanax anxiety 0.5 mg public speaking viagra round brown pill viagra treatment valtrex videos weight loss hair loss propecia fastin adipex overnight 89 buspar clomipramine diazepam feline evista 2007 meridia baikal lose weight lexapro experiences on wellbutrin xl online viagra purchasing ambien toxic dose asian pharmacies vardenafil cat on prednisone for asthma buy cheap lexapro lexapro sideaffects dosing amoxicillin dental abscess phentermine online without prior prescription metformin prophylaxis for type ii diabetes ambien cr's patent small intestine ulcers and metformin online viagra store meridia better phentermine celexa pain management xanax and clonozopam reaction celexa with adderall valium clonipin xanax is levitra safer than viagra effexor wellbutrin ultram home gym phentermine online progreso meridia euphoria from phentermine cialis generic mt tadalafil will i gain weight taking zyban prozac soma boards chongqed difference between phendimetrazine phentermine phentermine overnight no script black hole phentermine famvir tramadol wetrack it finasteride and male infertility phentermine that accepts cod payment soma alcohol oxycontin wellbutrin and panic attacks xenical hgh phentermine quit smoking pravachol bontril cialis celexa versus fluoxetine wellbutrin quit smoking xanax vs ativan benifits ambien cr patient info xanax with levitra evista and memory prednisone fluid acyclovir information on healthline paxil vs wellbutrin infertility metformin sleeping pills buy ambien lexapro and tmj valium and vicodine zyrtec zyrtec foradil phentermine evista klonopin and ambien to sleep hair growth shampoo finasteride cialis viagra levitra phorum view topic soma vs tramadol stop span viagra clonazepam vs diazepam naproxen with augmentin manufacture valacyclovir pcr ambien cr no rx valtrex xenical lexapro prilosec xanax detox euphoric effects from soma fosamax patent expiry ambien in drug tests cialis generic viagra no prescription needed overnight shipping phentermine bells palsy prednisone prozac night sweats long term prednisone dosage canine prozac ritalin xxx ultram tgp taking prozac and wellbutrin together valium versus klonopin piogitazone and metformin phentermine on line consultation generic paxil paroxetine buy mexico acyclovir infiltrate metformin off label use g3721 xanax picture evista versus fosomax is beer and prozac that bad pmr prednisone dosage atenolol glucose test ativan in veterinary use u 5672 viagra how long does ultram withdrawal take phentermine 37 mg buy safe online glucophage help get preg with pcos oral amoxicillin for mastoiditis st john's wort prozac wellbutrin found in bowel movement how xanax to take soma sun pilates celexa versus paxil for anxiety knockoff cialis prozac to celexa synthroid 50 mcg does tetracycline help acne prednisone swelling legs evista or fosamax prozac helps with food allergies prozac irritable angry viagra fast shipping valacyclovir pronunciation generic elavil picture image tripta viagra kamagra cialis what is augmentin 1000 used for overnight phentermine with saturday delivery zithromax and adverse effects to baby adderall and ativan methods on tamoxifen and receptors valacyclovir 500 mg cod diet phentermine pill shipped amnestic does of diazepam babys lungs and viagra does viagra expire what does tramadol hcl do xenical alli orlistat penegra generic viagra silagra penegra cumwithus amoxicillin absorbtion amount valium use and renal issues prozac and wellbutrin together adipex pharmacy online zanaflex and hydrocodone purchase clomiphene online with out a phentermine and trying to conceive cheap order paxil does fosamax cause constipation discontinue paxil cr treating bipolar with wellbutrin and trileptal lamisil patent expire myonlinemeds biz ultram ultram zyrtec viagra l477 still having hunger with adipex carisoprodol 500 count ativan nursing mother phentermine online no dr approval buy xanax without script weight lifting atenolol walmart pharmacy nexium viagra patanol online drug stores metrogel citratrate sildenafil viagra impotence hearing ambien cry celexa truth and side effects generic of xanax prednisone and metformin viagra supplies atenolol and low bp soma half-life ambien and xanax mixed with alcohol diazepam viscous solution amoxicillin clavulanate potassium chewable child dosage phentermine online pharmacy phentermine buy phentermine affect cr paxil side valium and sleep tramadol ultracet wellbutrin weight gain side effects lexapro drug facts generic wellbutrin side effects hives viagra bangkok online phentermine prescription valtrex zyban vardenafil with out prescription free sildenafil citrate fast cheap 30mg phentermines can clomiphene effect the passing urine phentermine 37.5 free shipping alprazolam online from diet tablets phentermine viagra reaction time canine ultram dosing somas 44 pics phentermine us pharm no rx needed risks of prednisone in dogs estradiol hemihydrate no rx augmentin 875mg tab business class northwest airline soma is aloe vera used in metformin danger meridia phentermine usa non script buy cheap phentermine here propecia and bioidentical testosterone buy tadalafil with blood level test for ambien xanax side efftects ecstacy celexa oxazepam ultram two nexium generic viagra work lexapro side effects muscle twitching metformin ob mice ip phentermine diet pills results buy clomiphene citrate buy soma 350 mg online tramadol habit forming ambien addition sudden reduction in prednisone ativan sublingual .5mg negative effects of xanax and valium can you mix xanax and codeine where can i purchase soma order tadalafil sale online meridia chat room prescription free phentermine how much does xenical cost tadalafil levitra generic viagra soma picture frame minoxidil finasteride after hair transplant seritonin syndrome prozac paxil diabetis byetta glucophage avandia viagra joke of the day buy prednisone with out a prescription generic viagra review lexapro drug interaction warnings bartonella zithromax metformin 750mg er ambien and xanax together glucophage weight ambien zr prednisone how supplied three day diet adipex diet pill nexium drugs viagra or cialis prices is xanax safe adipex phentermine online dr approval valium while pregnant prozac par irritability ambien viral disease zovirax order temp soma slippers hiv viagra lexapro package insert meatholes soma atenolol and impotence effects side sexual flight northwest airline soma 175 danger levitra 252 buy steriods phentermine lexapro cause high blood pressure nicorette wellbutrin nicotrol nicoderm zyban fluoxetine dose 40mg ativan drug rehab programs wellbutrin xl and depakote prednisone loose bloody stool carisoprodol carisoprodol 350mg crazy meds wellbutrin drug interactions ativan scopolamine prozac benadryl and prednisone where to buy phentermine cheap prozac candace pert evista ibuprofen caution protein bound pdr atenolol xanax without a prescription overnight delivery atenolol 25mg high blood pressure yeast lamisil key levitra metformin manfacturers lexapro prozac vs damge from nexium how to heal taking yourself off of paxil vicodin viagra cialis sildenafil citrate overseas amoxicillin gluten adipex interactions fischer soma boots how can i find tadalafil adipex diet plan celecoxib depigmentation wild thing prozac zenerx natural viagra statistics on prozac nexium and protonix studies phentermine without a presecription ultracet no prescription zoloft vs celexa diffrence in medication discount valacyclovir alcohol with alprazolam diet online phentermine pill purchase elavil picture false positive drug tests ambien lexapro storage polar disorder levitra vardenafil bargain prices monopril vs atenolol prozac nation read online wellbutrin effects on synthroid vardenafil patent levitra prednisone poison oak diazepam oral generic wellbutrin efficacy ambien prescription carisoprodol paxil cns effects celexa valium consumer information about phentermine valium have side effects amoxicillin allergic reaction symtoms benefits risks of the drug metformin loose stool synthroid prednisone upjohn valium or xanax when was lorazepam found video viagra cheapest phentermine quicktopic document review itchy rash prednisone not helping wellbutrin lexapro side effects alprazolam buy lexapro weight gain experiences diazepam mylan 345 prednisone for sunburn collect on delivery valium ultram test can you take prozac with ibuprofin same as viagra over the counter is klonopin water soluble tramadol without prescription ups shipping wellbutrin and auditory hallucinations metformin corosolic xanax online legal inexpensive tadalafil phentermine 24 hour adipex online no rx brenda antibiotic amoxicillin diazepam enema buy diazepam overseas what do you use carisoprodol for metformin pcos and pregnancy bell's palsy prednisone acyclovir valium 0554 xenical and poop metformin and prediabetes ultram controlled substance levitra without a prescription proscar finasteride xanax street value mrsa tetracycline acyclovir en espanol valerian root celexa stories of couples using drug levitra valium or xanax to treat dystonia buy vardenafil purchase vardenafil vardenafil tadalafil sildenafil citrate cheap celexa and vasodepressor syncope clonazepam message boards problems with lexapro finasteride half-life propecia specifications prozac takes weeks full effect zanaflex to soman effective ativan lamictil acyclovir reynaud's phenomenon valium 2nd day delivery diazepam prescribing inforomation wellbutrin sr bupropion washington phentermine breast feeding premarin provera clomiphene famvir ultram acyclovir taking xanax an lexapro together viagra tarket market paxil side effects in children cialis free consultation buy xanax valium online wellbutrin success forum finder air travel finder soma tetracycline treatment chlamydia ativan overnight delivery no prescription prednisone's effects on hypothyroidism paxil effects of long term use rapid absorption of synthroid lexapro en espano prescription medication soma in fla anyone taking phentermine yellow boots viagra drug interactions lisinopril adn wellbutrin treatment for molluscum contagiosum zovirax soma crystal bottle ambien sleeping mdicine xanax dosage dog viagra testosterone series side effects of lexapro wellbutrin withdrawal issues tadalafil drugstore generic viagra next day shipping femring estradiol order lamisil prescription led flashlights made by soma augmentin and otc cold medicines solutions for bruxism with clonazepam marketing ideas for viagra scab picking lexapro amoxicillin on line doctors for prescriptions prescritpion phentermine manufacturers of tamoxifen sildenafil side effects women i am thyroid synthroid and bontril buy sildenafil viagra rimadyl tramadol ambien health buying ultram no prescription generic valium xanax cheap halflife of elavil zoloff paxil any sexual side affects atenolol no prescription natural viagra scam lump in thoat adipex lorazepam life cycle wavy soma 2410 problem swallowing lexapro tramadol conversion to fentanyl patch australia support zyban carisoprodol or skelaxin emphysema and xanax lorazapam and soma orderr synthroid w o prescription viagra use longterm side effects from propecia tadalafil with sildenafil phentermine south america difference between valium and versed side effects lexipro and celexa synthroid sexual side effects ativan and aricept wellbutrin anxiety and social ativan causes acid reflux methylprednisolone vs prednisone injecting levitra