views:

117

answers:

2

So I thought this should be easy, but, I'm n00bing out here and failing epicly (as they say on teh interwebz).

So 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

+1  A: 

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
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 Webb-Heller
Just re-read your answer... and comprehended it a bit more :D thanks, I'll see where I can go with it.
Jack Webb-Heller
@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
A: 

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

Stolz