Pass variable number of variables to a class in PHP

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

    <?php
    
    class test
    {
      private $myarray = array();
    
      function save($index, $value)
      {
          $this->myarray[$index] = $value;
      }
    
      function get($index)
      {
         echo $this->myarray[$index] . '<br />';
      }
    }
    
    $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.

    0 讨论(0)
提交回复
热议问题