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) {
开发者_Go百科 $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?
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;
}
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
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;
}
精彩评论