【问题标题】:PHP - Why does including a function from another file fail?PHP - 为什么包含来自另一个文件的函数会失败?
【发布时间】:2011-09-24 20:52:51
【问题描述】:

我正在尝试将一个 PHP 文件中的一个函数包含到另一个 PHP 文件中,并将该函数与一个参数一起使用并获取一个返回值。一切都很好,直到我运行 PHP 死掉的函数。我该如何解决这个问题?

timestamp_reader.php:

<?php
function get_time($timestamp){
    $year = substr($timestamp, 0, 4);
    $month = substr($timestamp, 4, 2);
    if(substr($month, 0, 1) == "0")
        $month = substr($month, 1, 1);
    $day = substr($timestamp, 6, 2);
    if(substr($day, 0, 1) == "0")
        $day = substr($day, 1, 1);
    $hour = substr($timestamp, 8, 2);
    if(substr($hour, 0, 1) == "0")
        $hour = substr($hour, 1, 1);
    $hour = intval($hour);
    if($hour > 12){
        $hour = $hour - 12;
        $pm = true;
    }else $pm = false;
    $minute = substr($timestamp, 10, 2);
    if(substr($day, 0, 1) == "0")
    $day = substr($day, 1, 1);
    if($pm) $minute .= " PM";
    else $minute .= " AM";

    return $month . "/" . $day . "/" . $year . " " . $hour . ":" . $minute;
}
?>

以及我想要访问此功能的文件(注意,它位于不同的目录中):

...some PHP code before this...
include "/project/includes/timestamp_reader.php";
while($row=mysql_fetch_array($result)){
    $msg = $row['message'];
    $timestamp = $row['timestamp'];
    $time = get_time($timestamp);
    echo "<p><center>" . $time . " " . $msg . "</center></p>";
}

我想弄清楚这一点并将其用于各种功能,因此如果可能的话,我不必每次都输入它们。另外,我需要类似的东西来创建项目范围的变量。

无论如何,感谢您的所有帮助!

【问题讨论】:

  • 错误信息是什么?
  • 看起来在这里使用date() 和strtotime() 会更好。
  • 错误信息是什么? PS,在你的SELECT 语句而不是PHP 中用SQL 进行时间格式化可能会更整洁。 (假设您使用的是 MySql:dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html)
  • Firefox 告诉我解析“过滤器”值时出错。声明被放弃。在错误控制台中。
  • @Richard,firefox 的控制台与 php 错误有什么关系?

标签: php function include


【解决方案1】:

如何避免重新发明轮子? .. 特别是这样畸形的一个:

【讨论】:

    【解决方案2】:

    为什么不在 PHP 中使用 date() function?

    例如,

    $timestamp = "1316922240";
    echo date("m-j-Y", $timestamp);
    

    现在将根据该时间戳打印 09-24-2011 - 如果时间戳来自昨天,则回显的日期将是昨天。

    【讨论】:

      【解决方案3】:

      尝试使用 require(),如果路径错误,它会失败,我敢打赌就是这种情况。

      【讨论】:

      • 当您包含一个带有函数的文件时,require_once() 在这种情况下会更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 1970-01-01
      • 2020-12-24
      相关资源
      最近更新 更多