date function into a class doesn't work [close

2019-03-06 01:28发布

问题:

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);
    }

}

Ok, here is the full class...

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;  
        }
    }

}

...and how I call it :

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());

回答1:

You are probably confused why the method doesn't return what you wanted to.

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.

Rename your method test to something different, initialize class, and call that new method like:

$obj = new Test;
echo $obj->new_method(time() + 3600);