将数据数组传递给 CodeIgniter/PHP 中的私有函数?
所以我认为这应该很容易,但是,我在这里挣扎......
这是我的代码:
function xy() {
$array['var1'] = x;
$array['var2'] = y;
echo $this->_z;
}
function _z($array) {
$xy = $x.$y;
return $xy;
}
那么,为什么这个看似简单的代码不起作用?我知道使用视图可以传递数组,并且可以在视图中仅使用数组标题访问变量,但是,为什么它在这种情况下不起作用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关于从函数访问数组到私有函数的最佳解释之一。感谢代码帮助了我
{
$arrayVariable = "你想要传递的值";
函数
_toPrivateFuction($arrayVariable)
{
// 或打印来检查是否获得了所需的结果
// 如果是,那么您就可以开始了!
}
One of the best explanation about accessing array from a function to a private function. thanks the code helped me
{
$arrayVariable = "value you want to pass";
}
function _toPrivateFuction($arrayVariable)
{
// or print to check if you have the desired result
// if yes then you are ready to go!
}
您可以使用 PHP 原生函数 extract() 模仿您想要的 CI 视图行为(CI 就是这样做的)
参考:http://php.net/manual/en/function.extract.php
You can mimic the CI views behavior you want with the PHP native function extract() (That is how CI does it)
Reference: http://php.net/manual/en/function.extract.php
因为
function_z
不是视图。使用$this->_z($array);
调用它。视图也由 CodeIgniter 处理并将变量传递给它们。这对于非视图的工作方式不同。 PHP 不会自动为您执行此操作。要加载视图,请在
/system/application/views/
中创建一个视图文件,并使用$this->load->view('my_view_name', $array);< 调用它/code>
我将重写你的函数如下:
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: