Pass variable number of variables to a class in PHP

前端 未结 7 1837
别跟我提以往
别跟我提以往 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:54

    You can use an array to pass variable number of variable to the class, for example:

    myarray[$index] = $value;
      }
    
      function get($index)
      {
         echo $this->myarray[$index] . '
    '; } } $test = new test; $test->save('1', 'some value here 1'); $test->save('2', 'some value here 2'); $test->save('3', 'some value here 3'); $test->get(1); $test->get(2); $test->get(3); ?>

    Output

    some value here 1
    some value here 2
    some value here 3
    

    You could also use the __get and __set magic methods to save info easily.

提交回复
热议问题