简体   繁体   中英

Dynamically load class by name in Zend 2

I am currently trying to get an instance of a class by its name. I have a controller and in this controller i would like to get an instance of a class by its classname . I know that the class will be in the namespace MyModule\\Entity .

What is the best way to dynamically create an instance of a class with Zend 2 ?

namespace MyModule\Controller;

class MyController extends AbstractActionController {

public function indexAction() {
    $className = "myclass"; // File myclass.php
    $class = ??? // create instance by $className
    $class->process();
}

In ZF1 I would do

$class = new MyModule_Entity_Classname();

I don't know if this changed in ZF2.

If you use composer and it's configured properly you can use:

$class = new $className;

but $className should be full name of class, eg \\MyModule\\MyClass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM