PHP build-in class does not work in Cakephp 3.0

Asked

Viewed 80 times

2

I’m trying to use a class Built-in of PHP inside Cakephp but a:

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

Official documentation link where I saw this class being used: Documentation

  • Try to put a bar first, new \DateTime('today')

  • @rray Wizard.... submit a reply, whenever you want to use a built-in class I must use this \ ?

  • It’s the same problem of Namespace and PDO = Error

1 answer

3


To call php native classes inside a namespace you need to add a toolbar(\) before the name, so php knows it needs to call a class/function from core and not one with the same name that may be within the current namespace.

Change:

new DateTime('today')

To:

new \DateTime('today')

Example, without the slider 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();

Exit:

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

Example with the slider indicating that this class is from core

Altering:

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

Exit:

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)
  • 1

    You may also declare use DateTime shortly after namespace teste. I use this alternative as a convention for the use of native classes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.