简体   繁体   中英

Php require() does not recognize aliased class

So mainly this is caused by my code structure:

File1.php

use \Class1 as Blah;
require 'File2.php';

File2.php

$closure = function ($arg) {
    return new Blah($arg);
};

Somehow the part behind ... as isn't recognized after using require() .

Namespace aliases are only valid within the file in which you write the use statement. The aliases do not transfer across file boundaries. If you want to use Class1 as Blah within File2.php, you need to put that statement at the top of File2.php.

is not recognized by the code - Slim is not a compiler, it is a framework.

The code will execute to the PHP compiler standards, therefore using the default.

use SomeNamespace\SomeClass as SomePrefix;

Will work no matter what you're trying to achieve. The require_once() method loads your PHP file holding the class, which I assume doesn't have a custom namespace since you're targeting the \\ directory.

If you're working inside a class then this might be your issue, your code should run similar to this after using the require_once() to load in the ParseMarkdownClass file.

use ParseMarkdownClass as Md;

class SomeClass
{
    public $container;

    public function __construct()
    {
        $this->container = (object)['m' => function() {
            return new Md();
        }];
    }
}

(new SomeClass())->$container->m()->...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM