r/PHPhelp • u/ww1223 • Jan 23 '26
Using PHPMailer: what is the difference between 'use' and 'require' statements?
I’ve recently started to experiment with PHPMailer to send code-generated emails via SMTP – successfully, to my surprise.
I copied the PHPMailer folder (downloaded from github) manually to my php folder, previously installed via Homebrew. I then copied some code examples from a PHPMailer tutorial, thus:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '/opt/homebrew/etc/php/8.4/PHPMailer/src/Exception.php';
require '/opt/homebrew/etc/php/8.4/PHPMailer/src/PHPMailer.php';
require '/opt/homebrew/etc/php/8.4/PHPMailer/src/SMTP.php';
… and after that used more example code snippets involving the $mail variable to configure and authenticate SMTP, compose the email and send it. I’ve omitted these as they contain my personal logins etc, and I don’t think they’re relevant to my question.
All of this works, but I’d like to understand more instead of just blindly having to follow the 'recipe'. In particular, although I understand the three ‘require’ statements which are obviously pointing to php libraries that were installed as components of the PHPMailer package, I don't understand the meaning or purpose of the two ‘use’ statements. I suspected they were associated with a Windows installation, since they contain backslashes, and were therefore redundant for my macOS installation. But if I comment them out then the code no longer works. They don’t seem to relate to any valid path set up on my machine (unlike the ‘require’ statements). Many thanks if anyone can help, and please note my level of php knowledge is beginner at best (which might be apparent from my question anyway).
Mac Mini M4
macOS Sequoia 15.5
PHP 8.4 installed via Homebrew
View all comments
Show parent comment
1
u/obstreperous_troll Jan 24 '26 edited Jan 24 '26
Just to expand on that and give OP some extra context on how it relates to
require, whereuseonly creates an alias, the other side of the coin is the autoloader, so that the first time one creates or references anything on a class, it results in PHP locating and loading the file, typically usingrequire. PHP has a built-in autoloader, but it doesn't know anything about namespaces, so usually we're using the one that composer creates when packages are installed. That one is in pure PHP, but its heavy optimization makes it not the most readable thing around. It's only about a dozen lines of code to write your own PSR-4 autoloader, and it's a good learning exercise.Would be kind of nice if PHP's docs were updated to stop referencing the now-defunct
__autoloadfunction... What's the point of the comments when the maintainers never ever ever read them?