用户
 找回密码
 入住 CI 中国社区
搜索
查看: 2843|回复: 4
收起左侧

[已解决] 【不懂就要多问】关于一个创建helper辅助函数的问题

[复制链接]
发表于 2011-11-2 20:29:56 | 显示全部楼层 |阅读模式
楼主今天比较懒,所以突发奇想仿照form helper函数做了一个div函数。
一直试验了一个小时 发现按照手册上所写的 MY_div_helper.php一直在报错,后来实在不行改成了 MY_form_helper.php。无报错
接下来直接在视图文件中使用
PHP复制代码
 
<style type="text/css"> .fu {width:300px;margin:60px;}</style>
<?php $nong = array ( 'class' => 'fu', );?>
<?php div_open($nong);?>
test
<?php div_close(); ?>
复制代码

完全没效果,查看网页源代码没有div。

MY_form_helper.php代码如下
PHP复制代码
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 if ( ! function_exists('div_open')){
        function div_open($attributes = array()){
                $CI =& get_instance();
               
                $div = '<div " "';
                $div .= _atts_to_string($attributes);
                $div .= '>';
               
                return $div;
                }
 }
 
if ( ! function_exists('div_close')){
        function div_close () {
                 
                return "</div>";
                }
        }              
               
if (!function_exists('_atts_to_string'))
{
        function _atts_to_string($attributes)
       
        {
                if (is_array($attributes) AND count($attributes) > 0)
                {
                        $atts = '';
 
                        foreach ($attributes as $key => $val)  
                        {
                                $atts .= ' '.$key.'="'.$val.'"';
                        }
 
                        return $atts;
                }
        }
}
 
复制代码

发表于 2011-11-2 22:21:37 | 显示全部楼层
<?php echo div_open($nong);?>
<?php echo div_close(); ?>
 楼主| 发表于 2011-11-2 23:33:55 | 显示全部楼层

~~

本帖最后由 E.TAXI 于 2011-11-2 23:58 编辑
qi_ruo 发表于 2011-11-2 22:21

~~学到了
但是为什么不可以自定义helper函数名呢?
p.s跟据楼上的提醒改进了一下代码。
PHP复制代码
 if ( ! function_exists('div_open')){
        function div_open($attributes = array()){
                 $CI =& get_instance();
               
                $div = '<div ';
                $div .= _atts_to_string($attributes);
                $div .= '>';
                print  $div;
                //return  $div;
                }
 }
 
if ( ! function_exists('div_close')){
        function div_close () {
                 
                print "</div>";
                }
        }      
 
复制代码

现在view试图只需 <?php div_open() ?> <?php div_close() ?>即可~~
发表于 2011-11-2 23:48:01 | 显示全部楼层
对于系统原来没有的helper 只需定义为 div_helper.php 就可以了 $this->load->helper('div');
只有在需要扩展系统的helper 的时候才需要要加前缀 MY_form_helper.php

评分

参与人数 1威望 +2 收起 理由
Hex + 2 回答完全正确,+2分~

查看全部评分

 楼主| 发表于 2011-11-3 00:09:37 | 显示全部楼层
qi_ruo 发表于 2011-11-2 23:48
对于系统原来没有的helper 只需定义为 div_helper.php 就可以了 $this->load->helper('div');
只有在需要扩 ...

get it~~

本版积分规则