简体   繁体   English

在 codeigniter 中将 arguments 传递给 function 时出现问题

[英]Problem passing arguments to function in codeigniter

I am using the CodeIgniter framework.我正在使用 CodeIgniter 框架。 I created a library called common_funtions .我创建了一个名为common_funtions的库。 This library enables me to call a function in different controllers.这个库使我能够在不同的控制器中调用 function。 One function in particular needs an argument, but I'm getting three errors when I call the function:一个 function 特别需要一个参数,但是当我调用 function 时出现三个错误:

A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for Common_functions::time_ago(), called in \...\get_comments.php on line 11 and defined
Filename: libraries/Common_functions.php
Line Number: 20

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: time
Filename: libraries/Common_functions.php
Line Number: 26

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: time
Filename: libraries/Common_functions.php
Line Number: 39

Here is my code: In the library: common_functions.php这是我的代码:在库中:common_functions.php

// The following function calculates ‘how long ago’
function time_ago($time)
{       
    $periods = array('second', 'minute', 'hour', 'day');
    $lengths = array('60', '60', '24', '7');
    $tense = 'ago';
    $now = time();
    $time_diff = $now - $time;
    for ($j = 0; $time_diff >= $lengths[$j] && $j < count($lengths)-1; $j++)
    {
        $time_diff /= $lengths[$j];
    }
    $time_diff = round($time_diff);
    if ($time_diff != 1)
    {
        $periods[$j].='s';
    }
    if ($time_diff > 7 && $periods[$j] == 'days')
    {
        $time_ago = date("l dS F, Y", $time);
    } 
    else 
    {
        $time_ago = $time_diff." ".$periods[$j]." ago";
    }
    return $time_ago;
}

In my controller:在我的 controller 中:

$query = $this->db->query(“
    SELECT * 
    FROM post_comments 
    WHERE p_id = ‘$id’ 
    ORDER BY date ASC”);
$comments = $query->result_array();
foreach ($comments as $comment)
{
    $comment['date'] = $this->common_functions->time_ago($comment['date']);
}

Is there something wrong with my code?我的代码有问题吗? Or maybe it's a bug in my framework?或者它可能是我框架中的一个错误? This is not the first time I'm experiencing this.这不是我第一次遇到这种情况。

Have you loaded the library with $this->load->library('common_functions');您是否使用$this->load->library('common_functions');加载了库? ? ?

Also it seems in this situation, you would be more suited to use a model rather than a library, see: http://codeigniter.com/user_guide/general/models.html在这种情况下,您似乎更适合使用 model 而不是库,请参阅: http://codeigniter.com/user_guide/general/models.ZFC35FDC70D5FC69AD269883A8EZ7C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM