Search code examples
phpcodeigniterfunctionprivate-functions

Passing an array of data to a private function in CodeIgniter/PHP?


So I thought this should be easy, but, I'm struggling here...

Here's my code:

function xy() {
  $array['var1'] = x;
  $array['var2'] = y;
  echo $this->_z;
}

function _z($array) {
  $xy = $x.$y;
  return $xy;
}

So, why doesn't that seemingly simple code work? I know with views you can pass arrays and the variables are accessible in the views with just their array title, but, why doesn't it work in this case?


Solution

  • Because function _z is not a view. Call it with $this->_z($array);. Also views are processed by CodeIgniter and variables passed into them. This doesn't work the same way for non-views. PHP won't do that automatically for you.

    To load a view make a view file in /system/application/views/ and call it with $this->load->view('my_view_name', $array);

    I would rewrite your functions as follows:

    function xy()
    {
        $x = "some value";
        $y = "some other value";
    
        echo $this->_z($x, $y);
    }
    
    function _z($a, $b)
    {
        return $a.$b;
    }