Created
June 17, 2010 19:27
-
-
Save jeremeamia/442647 to your computer and use it in GitHub Desktop.
Find last child class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // This script is an example of how you can find the last item in a non-branching inheritance hierarchy | |
// Declaring classes | |
class food {} | |
class cheese extends food {} | |
class cheddar extends cheese {} | |
class white_cheddar extends cheddar {} | |
// Finds the last child in a non-branching inheritance hierarchy | |
function get_last_child($parent) | |
{ | |
$pool = array($parent => count(class_parents($parent))); | |
foreach (get_declared_classes() as $class) | |
{ | |
if (is_subclass_of($class, $parent)) | |
$pool[$class] = count(class_parents($class)); | |
} | |
return array_search(max($pool), $pool); | |
} | |
// Creates a class at the end of a non-branching inheritance hierarchy | |
function define_child_class($class, $parent) | |
{ | |
eval($php='class '.$class.' extends '.get_last_child($parent).' {}'); | |
return class_exists($class) ? $class : FALSE; | |
} | |
// Testing | |
if ($class = define_child_class('glowing_cheddar', 'cheese')) | |
{ | |
echo '<h3>Parents of <code>'.$class.'</code>:</h3><pre>'.print_r(class_parents($class), TRUE).'</pre>'; | |
} | |
else | |
{ | |
echo 'Failed.'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment