Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't 'use' statement be in include file?

Tags:

php

Why can't my use statement be placed inside an include file?

This works fine:

require_once("PHPMailer_Loader.php");

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

SendEmailWindows("[email protected]", "smtp test", "test body");

function SendEmailWindows($emailTo, $subject, $body){
    $mail = new PHPMailer;
    [... all the rest of the function code]
}

Yet when I try to move those 2 use statements into my PHPMailer_Loader.php script (placed at the very bottom of the file), it breaks with this error:

Fatal error: Class 'PHPMailer' not found in [...]\EmailTester.php on line 12

Just for tidyness and compactness I'd like to move everything into the include except for the function and the calling line.

like image 788
HerrimanCoder Avatar asked Oct 26 '25 15:10

HerrimanCoder


1 Answers

The PHP manual is saying this:

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. [...] Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

The "Importing rules are per file basis" part being the important one here.

You can use PHPMailer\PHPMailer\PHPMailer in your include file, but that only means that PHPMailer (without having to specify the full class name) will be available inside your include file and not in the parent file (the one which includes your include file).

tl;dr

You need to specify your use ...; statements in every file you want that specific use to apply.

like image 63
Smuuf Avatar answered Oct 29 '25 04:10

Smuuf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!