我可以使用转换日期(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()(以前在..中声明
我该如何做到这一点?为什么会发生这种情况谢谢。
您已经将函数定义本身放入了一个循环中。例如:
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
}
EDIT根据您在下面的评论,以下是如何重写该代码以使用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
变量是对象,它是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,所以我不会在这里讨论它,谷歌将是一个起点。我要说的一件事是,如果你想理解OOP,PHP不是一个起点。PHP不是一种OO语言,而是一种提供OO支持的脚本语言。我将为您指明Java学习如何在OO中思考的方向,尽管其他人可能也会不同意。
您应该在循环之前声明函数。您首先声明一个名为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
}
函数是否在while循环中声明?如果是这样的话,它将为每个循环迭代声明一次,并且由于函数只能声明一次。这将导致您描述的错误。
如果是这种情况,您可以简单地在循环外声明函数(可能与其他辅助函数在不同的文件中),并在循环内调用它,而不会出现任何问题。