我在视图中有一个函数(我嵌套了代码,所以没有其他选择)。我的问题是因为我想在函数中添加一些变量。
我无法访问函数中的var。
<div>
<?php _list($data); ?>
</div>
<?php
echo $pre; // Perfect, it works
function _list($data) {
global $pre;
foreach ($data as $row) {
echo $pre." ".$row['title']; // output ' title' without $pre var
if (isset($row['childrens']) && is_array($row['childrens'])) _list($row['childrens']);
}
}
?>
简单。。。只需这样定义函数:
function _list($data, $pre=NULL)
然后在函数内部,您可以检查$pre是否为NULL,然后在其他地方搜索它。。。在函数中使用全局语句是不可取的。
另一方面,您可以define('pre',$pre);
并使用在函数中创建的预常量。。。同样不可取,但它对你的例子有效。
后期编辑:在HELPERS中定义您的功能我不知道为什么我首先忘记了建议
视图中的定义函数很奇怪。使用全局变量会使情况变得更糟。
也许你应该避免使用全局函数:
<div>
<?php
foreach($data as $row){
_list($pre, $row);
}
?>
</div>
<?php
function _list($pre, $row) {
echo $pre." ".$row['title'];
if (isset($row['childrens']) && is_array($row['childrens'])){
foreach($row['childrens'] as $child){
_list($pre, $child);
}
}
}
?>
顺便说一句,在助手中定义函数会更好
http://ellislab.com/codeigniter/user-guide/general/helpers.html
它们帮助的原因