Pass variable number of variables to a class in PHP

前端 未结 7 1661
别跟我提以往
别跟我提以往 2021-02-14 14:12

I need to pass a variable number of strings to instantiate different classes. I can always do a switch on the size of the array:

switch(count($a)) {
case 1:
            


        
相关标签:
7条回答
  • 2021-02-14 14:29
    // Constructs an instance of a class with a variable number of parameters.
    
    function make() { // Params: classname, list of constructor params
     $args = func_get_args();
     $classname = array_shift($args);
     $reflection = new ReflectionClass($classname);
     return $reflection->newInstanceArgs($args);
    }
    

    How to use:

    $MyClass = make('MyClass', $string1, $string2, $string3);
    

    Edit: if you want to use this function with your $a = array("variable1", "variable2", 'variable3", ...)

    call_user_func_array('make', array_merge(array('MyClass'), $a));
    
    0 讨论(0)
  • 2021-02-14 14:30

    If you must do it this way, you can try:

    $variable1 = 1;
    $variable2 = 2;
    $variable3 = 3;
    $variable4 = 4;
    
    $varNames = array('variable1', 'variable2', 'variable3', 'variable4');
    $reflection = new ReflectionClass('A');
    $myObject = $reflection->newInstanceArgs(compact($varNames)); 
    
    class A
    {
        function A()
        {
            print_r(func_get_args());
        }
    }
    
    0 讨论(0)
  • 2021-02-14 14:33
    <?php
    
    new Example($array);
    
    class Example
    {
        public function __construct()
        {
            foreach (func_get_args() as $arg)
            {
                // do stuff
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-14 14:34

    Look here. Does method 2 help ? Also, perhaps by moving the switch to the constructor (if that is practical) you would be able to hide this from the rest of the code.

    0 讨论(0)
  • 2021-02-14 14:35

    have a look at the factory design pattern:

    class Factory {
      public static function CreateInstance($args) {
        switch(func_get_num_args()) {
          case …:
            return new ClassA(…); break;
          case …:
            return new ClassB(…); break;
        }
      }
    }
    
    0 讨论(0)
  • 2021-02-14 14:51

    It seems that reflection can pull this one out of the hat for you. This comes to you courtesy of the PHP call_user_func_array notes. The following code will create a class by calling the constructor with the contents of your array.

    <?php
    // arguments you wish to pass to constructor of new object
    $args = array('a', 'b');
    
    // class name of new object
    $className = 'ClassName';
    
    // make a reflection object
    $reflectionObj = new ReflectionClass($className);
    
    // use Reflection to create a new instance, using the $args
    $command = $reflectionObj->newInstanceArgs($args);
    // this is the same as: new myCommand('a', 'b');
    
    ?>
    
    0 讨论(0)
提交回复
热议问题