PHP Build-in class does not work in CakePHP 3.0

2

I'm trying to use a class Built-in of PHP inside CakePHP but it's returned one:

  

Error: Class 'App \ Controller \ Component \ DateTime' not found

Where it's being used:

public function listNewBanners($newBannersQuantity)
{
    $newBanners = TableRegistry::get('new_banners');
    $query = $newBanners->find();
    $query->select(['path_banner', 'date_start', 'date_end'])
        ->where(['date_start <' => new DateTime('today')])
        ->limit($newBannersQuantity);
    return $query;
}

Link to official documentation where I saw this class being used: Documentation

    
asked by anonymous 30.07.2015 / 19:23

1 answer

3

In order to call native php classes inside a namespace it is necessary to add a slash ( \ ) before the name, so php knows that it needs to call a core class and function one with the same name that might be within the current namespace.

Change:

new DateTime('today')

To:

new \DateTime('today')

Example, without the slash or will try to call the current namespace class if it exists or will return nome da classe not found

<?php

namespace teste;

class Teste{
    public function __construct(){
         echo '<pre>';
         var_dump(new DateTime());
    }
}

class DateTime{
    public function __construct(){
        echo 'minha DateTime personalizada';
    }
}

new Teste();

Output:

minha classe personalizada
object(teste\DateTime)[2]

Example with the bar that indicates that this class is core

Change:

class Teste{
    public function __construct(){
         echo '<pre>';
         var_dump(new \DateTime());
    }
}

Output:

object(DateTime)[2]
  public 'date' => string '2015-07-30 20:02:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Berlin' (length=13)
    
30.07.2015 / 19:47