Question

Hello I am trying to create my own custom helper class to use with Yii2. It is going to handle times so I'll be working with PHP's DateTime class. I have

<?php

namespace yii\helpers;

use Yii;

class Time
{
    public static function getTime()
    {  
    $time = new DateTime('now', new DateTimeZone('UTC'));
    return $time->format('m-d-Y H:i:s');
    }
}

To test it I added use yii\helpers\Time; to a view file and called Time::getTime(); but Yii2 throws an ErrorException saying Class 'yii\helpers\DateTime' not found.

The php DateTime object works fine if I place the code directly into a view file and execute it so I'm not sure what my problem is.

Was it helpful?

Solution

Put a backslash in from of the class name to indicate it is in the global namespace:

$time = new \DateTime('now', new \DateTimeZone('UTC'));

OTHER TIPS

Add use for DateTime:

use Yii;
use DateTime;

See use "global-namespace";

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top