1

我可以使用以下方法转换日期(2011-01-05 到 2011 年 1 月 5 日):

<?php   
$whatever = get_post_meta($post->ID, start_date, true);
$nice_date = date("d F Y", strtotime($whatever));
echo $nice_date;
?>

但是,我想在一个函数中实现它,这样我就可以在不同的地方使用它:

<?php   

function newDate($whatever) {
$nice_date = date("d F Y", strtotime($whatever));
return $nice_date; }

$crap_date = get_post_meta($post->ID, start_date, true);
echo newDate($crap_date);

?>

该函数位于 while 循环 (WordPress) 中。第一个日期的格式正确,但第二个我收到以下错误消息:

致命错误:无法重新声明 newDate()(之前在..

我将如何进行这项工作,为什么会这样?谢谢。

4

3 回答 3

2

您应该在循环之前声明该函数。您首先声明一个名为 newDate 的函数,然后随时随地使用它,但是您不能再次声明具有相同名称的函数(这正是您function newDate(..){....}在循环中编写时发生的情况。

function newDate($whatever) {
$nice_date = date("d F Y", strtotime($whatever));
return $nice_date; }

$crap_date = get_post_meta($post->ID, start_date, true);
echo newDate($crap_date);

//Here goes the loop
while( $i < 100)
{
  //do something with the newDate function
}
于 2012-03-08T14:16:52.843 回答
2

函数是否在 while 循环中声明?如果是这样,它将为每次循环迭代声明一次,并且由于一个函数只能声明一次,这将导致您描述的错误。

如果是这种情况,您可以简单地在循环外声明该函数(可能在具有其他辅助函数的不同文件中)并从循环内部毫无问题地调用它。

于 2012-03-08T14:18:55.570 回答
2

您已将函数定义本身放入循环中。例如:

while ($someCondition) {

  function newDate () {

    // Function code

  }

  // Loop code

}

这会尝试在循环的每次迭代中重新声明函数,这将导致您看到的错误。

将函数定义包装在if

while ($someCondition) {

  if (!function_exists('newDate')) {
    function newDate () { 

      // Function code

    }
  }

  // Loop code

}

或者(更好)在循环之前声明函数:

function newDate () { 

  // Function code

}

while ($someCondition) {

  // Loop code

}

编辑根据您在下面的评论,以下是如何重写该代码以使用该DateTime对象:

function format_date ($dateStr, $formatStr = 'd F Y') {
  $date = new DateTime($dateStr);
  return $date->format($formatStr);
}

$crap_date = get_post_meta($post->ID, 'start_date', true);
echo format_date($crap_date);

这个函数接受一个可以被DateTime对象解析的任何日期格式的字符串作为它的第一个参数(我认为使用与 相同的内部机制strtotime())。可选的第二个参数是与date()函数的第一个参数相同的格式字符串 - 如果省略,d F Y将使用默认值。

关于您的 OOP 问题:

Is this approach better?- 这在很大程度上是一个见仁见智的问题。我看到它在这里评论说DateTime对象比strtotime()/date()方法更好,反之亦然,但这归结为你应该使用你最了解的方法,对给定情况最有意义的方法,以及一种使您的代码对您和您可能与之合作的其他开发人员来说最易读的方法。我从来没有见过一个令人信服的论据,证明一个人肯定比另一个人更好。对于上面的例程,我认为它没有太大区别。

How could I rewrite my function in that format?- 看上面。

Is DateTime the object and format the method to change a property?-DateTime是一个的名称。在上面的示例代码中,$date变量是一个object,它是class的一个实例。是的,是一个方法的名称。DateTime format

Would this help me understand OO better if I will try and write all the code in this approach, where possible?- OOP 需要一种不同于编写程序代码的思维方式,而且这不是一件容易上手的事情。有很多很多资源可以帮助您掌握 OOP,所以我不会在这里深入探讨,Google将是开始的地方。我要说的一件事是,如果你想了解 OOP,PHP 不是开始的地方。PHP不是OO 语言,它是一种提供 OO 支持的脚本语言。我会向您指出 Java 的方向,以学习如何在 OO 中思考,尽管其他人可以并且会不同意。

于 2012-03-08T14:19:02.313 回答