Mr. Felix Mr. Felix - 2 months ago 9
PHP Question

Importing custom class inside a controller

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

<?php
class Hi
{
function __construct(){ }

public function hi()
{
echo "hi!";
exit;
}
}


Then in a controller, I tried to include it:

<?php
namespace App\Controller;

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

class MyController extends AppController
{
public function sayHi()
{
$a = new Hi();
$a.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?

MyController.php
and
Hi.php
are in the same folder. I'm using PHP 7.

ndm ndm
Answer

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

http://php.net/...namespaces.importing.php#language.namespaces.importing.scope

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.

http://www.php-fig.org/psr/psr-4/

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 {
    // ...
}

in

src/Utils/Hi.php