Addo Solutions
Addo Solutions

Reputation: 1637

Nested Dynamic PHP Class

I may just need a terminology update, but I have been playing in Magento and Joomla, and they do references like

$mage = new Mage;
$mage->block('blockname');

where class Mage through some process I am failing to figure out is calling:

class blockname extends something{

}

Don't quote me on that code, however I am looking to do something like that where I have a file that I can do $myscript->block('blockname'); and it will load and call the file with class blockname.

Upvotes: 2

Views: 89

Answers (1)

Artefacto
Artefacto

Reputation: 97845

class Mage {
    private $block;

    public function block($blockname) {
        if (!class_exists($blockname, true)) {
            throw new InvalidArgumentException("Not a valid class name: $blockname");
        }
        $this->block = new $blockname;
    }
}

The loading of the class definition (if not already done) is typically accomplished through autoloading (see here).

Upvotes: 3

Related Questions