Code

Classy Names

To continue my crazy development schemes of abstracted goodies I’ve found the following code slice to be of particular interest:

class test
{
        public $fubar;
 
        function __construct()
        {
                return true;
        }
 
        function Foo()
        {
                $this->fubar = "bar";
        }
 
        function Bar()
        {
                $this->fubar = "foo";
        }
 
        function __toString()
        {
                return "Value: " . $this->fubar . "";
        }
}
 
class nack extends test
{
        function __toString()
        {
                return "NACK QUACK! " . $this->fubar . "";
        }
}
 
$classname = array("test", "nack");
 
foreach( $classname as $classy )
{
        $runtime = new $classy();
 
        $runtime->Foo();
        echo $runtime;
        $runtime->Bar();
        echo $runtime;
}
?>

The results should be:

Value: bar
Value: foo
NACK QUACK! bar
NACK QUACK! foo

This demonstrates creating and running classes from variable names, something I’ve had to hack away at recently. Since the names are also stored in array form you could even go about creating a “trigger” like mechanism and do an array_walk (example assumes the class definitions are intact):

function runtime_name($item1)
{
        $runtime = new $item1();
 
        $runtime->Foo();
        echo $runtime;
        $runtime->Bar();
        echo $runtime;
}
 
echo "Walk it out!";
array_walk($classname, 'runtime_name');

The results of which look a lot like this:

Walk it out!
Value: bar
Value: foo
NACK QUACK! bar
NACK QUACK! foo

This method would allow you to re-use that “logic” multiple times throughout your program.