Mr. Felix Mr. Felix - 10 months ago 48
PHP Question

Importing custom class inside a controller

I created a class at Controller folder of Cake project like this:

class Hi
function __construct(){ }

public function hi()
echo "hi!";

Then in a controller, I tried to include it:

namespace App\Controller;

use App\Controller\AppController;
include_once "Hi.php";

class MyController extends AppController
public function sayHi()
$a = new Hi();

Here is the error I'm having:

Fatal error: Cannot declare class Hi, because the name is already in use in path\api\src\Controller\Hi.php on line 2

What's going on?

are in the same folder. I'm using PHP 7.

ndm ndm
Answer Source

Including a file won't make the classes in that file part of the current namespace, as namespaces are a per-file functionality.

Your Hi class will be declared in the global namespace, and your new Hi() will cause PHP to look for it in the current namespace, ie it will look for App\Controller\Hi, which doesn't exist, hence the composer autoloader kicks in, and will map this via a PSR-4 namespace prefix match to src/Controller/Hi.php, which will include the file again, and that's when it happens.

Long story short, while using new \Hi() would fix this, you better not include class files manually, or declare them in paths where they do not belong. Instead declare your files and classes in a proper autoloading compatible fashion, that is for example with a proper namespace in a path that matches that namespace, like

namespace App\Utils;

class Hi {
    // ...