日期函数到类中不工作 [英] date function into a class doesn't work
问题描述
我写了一个关于以不同格式/语言翻译日期的课程。但问题是,当我包括日期功能,它似乎无法正常工作。你知道为什么吗 ?我使我的代码更轻的基本知识,以了解问题:
I wrote a class about translating dates in different formats/languages. But the problem is when I include the date function into it, it seems not to work. Do you know why ? I made my code lighter with essentials in order to understand the problem :
class Test {
public function test($timestamp, $format='d/m/Y') {
return date($format, $timestamp);
}
}
...
class GetDateTime {
private $_text_en_US = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "January", "February", "March", "April", "May","June", "July", "August", "September","October", "November", "December");
private $_text_fr_FR = array("Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");
public function getDateTime($format='d/m/Y', $timestamp, $locale='fr_FR') {
switch ($format) {
case 'd/m/Y':
case 'm/d/Y':
return date($format, $timestamp);
break;
case 'l d F Y':
return str_replace($_text_en_US, ${'_text_'.$locale}, date($format, $timestamp));
break;
}
}
}
和我如何调用它:
include_once (BASE_DIR.'/lib/dateTime.class.php');
$dateTime = new GetDateTime();
事实是当我调用时它没有翻译:
The fact is it's not translated when I call :
echo $dateTime->getDateTime('l d F Y', date());
推荐答案
您可能会困惑为什么方法不返回你想要什么。
You are probably confused why the method doesn't return what you wanted to.
new Test(time())
不返回格式日期,因为方法 test
与类的名称相同,因此, test
方法成为该类的构造函数。您不能从构造函数返回值,因为在创建对象时,将返回对该对象的引用。
new Test(time())
doesn't return formated date, because method test
is the same name as class, and because of that, test
method becomes constructor of that class. You cannot return values from constructor, because when you create object, reference to that object is returned.
重命名您的方法 test
to something different,initialize class,并调用这个新方法,如:
Rename your method test
to something different, initialize class, and call that new method like:
$obj = new Test;
echo $obj->new_method(time() + 3600);
这篇关于日期函数到类中不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!