PHP Function of the Day (2011-9-23): class_parents

[fphp]class_parents[/fphp] returns an array with the class parents of the passed object. Not sure why this would be useful over the instanceof operator though…

(Yeah, some days I’m going to be asking “what’s this for?” rather than try to be all teachy and stuff).

In case you are into multiple inheritance, and have lost track of just how many times you wrote extends.

Use of this might be an indicator that you should think about favouring composition over inheritance.


interface bakeable {
function bake();
}

Class Cake implements bakeable {
function bake(){echo 'Oven is on ...';}
}

Class Sponge extends Cake {
function doSponge(){ echo 'Created sponge! '; }
}

Class LayerCake extends Sponge {
function make(){
$this->bake();
$this->doSponge();
echo 'Add jam! ';
}
}

$mmm = new LayerCake;
$mmm->make();
// Oven is on ...Created sponge! Add jam!

var_dump( class_parents($mmm) );
//array
//  'Sponge' => string 'Sponge' (length=6)
//  'Cake' => string 'Cake' (length=4)
var_dump( class_implements($mmm) );
// bakeable;

vs instanceof, instanceof is fine if you know which class you want to check for, whereas this shows all the class dependencies.

In this case you might know a little about the layer cake heirarchy, but - is there an Baker class? Is there an oven class that I need to evoke? Well now you can find out at runtime …

Off Topic:

…is it bad that the only thing today’s FotD did was make me hungry?

Hi, perhaps I could have explained my point slightly better …

In userland you will likely be faced with this scenario:


<?php

// classes are autoloaded

// ...
// load of code

$mmm = new LayerCake;
$mmm->make();

// load more code


So to find out at least the names of the classed being evoked are, you can at least do a simple:


var_dump(class_parents($mmm)) ;

Which will give you a lead as to which files you should be looking to open up in the case of a problem.