E.TAXI 发表于 2011-11-2 20:29:56

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

楼主今天比较懒,所以突发奇想仿照form helper函数做了一个div函数。
一直试验了一个小时 发现按照手册上所写的 MY_div_helper.php一直在报错,后来实在不行改成了 MY_form_helper.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代码如下
<?phpif ( ! 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;
                }
        }
}

qi_ruo 发表于 2011-11-2 22:21:37

<?php echo div_open($nong);?>
<?php echo div_close(); ?>

E.TAXI 发表于 2011-11-2 23:33:55

~~

本帖最后由 E.TAXI 于 2011-11-2 23:58 编辑

qi_ruo 发表于 2011-11-2 22:21 static/image/common/back.gif

~~学到了
但是为什么不可以自定义helper函数名呢?
p.s跟据楼上的提醒改进了一下代码。
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() ?>即可~~

qi_ruo 发表于 2011-11-2 23:48:01

对于系统原来没有的helper 只需定义为 div_helper.php 就可以了 $this->load->helper('div');
只有在需要扩展系统的helper 的时候才需要要加前缀 MY_form_helper.php

E.TAXI 发表于 2011-11-3 00:09:37

qi_ruo 发表于 2011-11-2 23:48 static/image/common/back.gif
对于系统原来没有的helper 只需定义为 div_helper.php 就可以了 $this->load->helper('div');
只有在需要扩 ...

get it~~
页: [1]
查看完整版本: 【不懂就要多问】关于一个创建helper辅助函数的问题