I have a contact form that uses PHPmailer.
It works if I write it like this:
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;
if($_REQUEST['action'] == 'contact'){
require 'vendor/autoload.php';
...
But, I only need the PHP mailer code when the contact form is being submitted. So what I want to do is see it /?action=contact is part of the url, and only if it is create the mailer objects. However, when I change the code to:
if($_REQUEST['action'] == 'contact'){
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;
require 'vendor/autoload.php';
...
I get
Parse error: syntax error, unexpected token “use” in C:Usersmorensourcereposfidiumpa.comindex.php on line 14
I even tried put the use commands in a file called test.php.
test.php
<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;
Then changing the code in index.php to:
if($_REQUEST['action'] == 'contact'){
require "test.php";
require 'vendor/autoload.php';
...
But then I get an error when it runs:
Fatal error: Uncaught Error: Class “PHPMailer” not found in C:Usersmorensourcereposfidiumpa.comindex.php:27 Stack trace: #0 {main} thrown in C:Usersmorensourcereposfidiumpa.comindex.php on line 27
It’s no longer a parse error, it’s more like the use commands don’t work when they are in test.php.
I’m going to look up what use does in PHP. I was thinking it was creating an instance of the object, but I’m thinking it might be like the using namespace std; in C++. I still don’t get why I can’t use it conditionally in an if block though. PHP isn’t a compiled language where it needs the libraries to compile the code, it’s a scripting language, shouldn’t it just run line by line and run the code as it comes?