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.
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).
You need to specify your use ...; statements in every file you want that specific use to apply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With