Black
Black

Reputation: 20232

How to include / require `use` operator statements?

I dynamically generate my use statements and try to include them.

use.php (Path: /App/Test/Use/use.php)

<?php
    use App\Http\Utility\GeneralUtility;
    use App\Models\Project;
    use App\Http\Selenium;
?>

PlayController.php (Path: /App/Http/Controllers/PlayController.php)

<?php

    namespace App\Http\Controllers;
    require app_path() . '\Projects\Test\Use\use.php';
    ...

However, If I try to use a included/required class in my controller then I get the info that some classes are missing. E.g.

FatalThrowableError in PlayController.php line 30:
Class 'App\Http\Controllers\Selenium' not found

Of course it works If I write them manually into the Controller without using require:

<?php
    namespace App\Http\Controllers;

    use App\Http\Utility\GeneralUtility;
    use App\Models\Project;
    use App\Http\Selenium;

    ...

So why does it not work if I include / require them?

Upvotes: 2

Views: 158

Answers (2)

Jarzon
Jarzon

Reputation: 652

Use is done at compile time and include at runtime, so that makes it impossible. But what you could do is, use something like PHP-Parser to replace the includes before the script is being executed.

Upvotes: 1

Nytrix
Nytrix

Reputation: 1139

It is not possible what you are trying to do. Here is the documentation from the PHP manual on it:

Note: Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

The source comes from here and the full documentation link is here.

Upvotes: 2

Related Questions