简体   繁体   中英

Using ReflectionClass in PHP, how do you use the passed parameters in the constructor?

So I have a class that I want to create with a dynamic amount of parameters (other classes it can use). This is dynamic because the site is fairly dynamic, and if I add a new class/plugin, I want my main class to be able to use it.

This is my code for creating the class:

$my_class = 'pages';
$my_parameters = array($class_mysql, $class_functions, $class_forms2);
$my_parameters = array_merge($my_parameters, $extra_classes);

$reflection = new ReflectionClass($my_class);
$class_pages = $reflection->newInstanceArgs($my_parameters);

The $extra_classes is an array that is created with the class instances of all active plugins that I want my pages class to be able to use.

This is all working fine, but I'm at a loss as to what to do in class file now. Here's what I had originally:

class pages {

    protected $class_mysql = null;
    protected $class_functions = null;
    protected $class_forms2 = null;

    public function __construct($mysql_instance, $functions_instance,
    $forms2_instance) {

        $this->class_mysql = $mysql_instance;
        $this->class_functions = $functions_instance;
        $this->class_forms2 = $forms2_instance;

    }

}

How do I work the passed dynamic parameters into this? I've been searching but can't find anything that makes sense to me. Even the PHP page on ReflectionClass stops at creating the instance of the class, and doesn't have an example of using the parameters in the class itself. Am I doing this right?

Ok, I'm not sure if I'm allowed to answer my own questions... but here's what I came up with after googling for about an hour and stumbling onto func_get_args()

class pages {

    protected $classes = array();

    public function __construct() {
        if (func_num_args() > 0) {
            $args = func_get_args();
            foreach ($args as $key => $value) {
                $this->classes[get_class($value)] = $value;
            }
        }
    }

}

This does what I needed to do. I can now check $classes to see what classes are available for pages to use, and can use those classes by using $this->classes['classname'] .

I don't know if this is the right way of doing this, so if anyone knows please comment. Thanks!

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