1

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?

Jack
  • 9,615
  • 18
  • 72
  • 112

3 Answers3

1

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;
}
Josh K
  • 28,364
  • 20
  • 86
  • 132
  • Thanks Josh, but, I don't want to load a view. I want to pass data to a private function for it to deal with, format accordingly, then return to be echoed from my public function. – Jack Jun 15 '10 at 12:15
  • Just re-read your answer... and comprehended it a bit more :D thanks, I'll see where I can go with it. – Jack Jun 15 '10 at 12:21
  • @Jack: You can't create an array of key values and pass it to a function and have them available by name (as it works in the views). I'll write some sample code. – Josh K Jun 15 '10 at 12:32
1

You can mimic the CI views behavior you want with the PHP native function extract() (That is how CI does it)

function xy() {
    $some_array = array(
        'foo' => 'Hello',
        'bar' => 'world'
    );
    echo $this->_z($some_array);
}

function _z($array) {
    extract ($array);
    $xy = "$foo $bar";
    return $xy;
}


xy();

Reference: http://php.net/manual/en/function.extract.php

Javi Stolz
  • 4,720
  • 1
  • 30
  • 27
0

One of the best explanation about accessing array from a function to a private function. thanks the code helped me

function _normal()

{ $arrayVariable = "value you want to pass";

echo $this->_toPrivateFuction($arrayVariable);

}

function _toPrivateFuction($arrayVariable) {

// or print to check if you have the desired result

print_r(arrayVariable);

// if yes then you are ready to go!

return $arrayVariable;

}