Search code examples
phpphpmailer

PHP class - PHPMailer unexpected 'use' (T_USE)


I would to like use the PHPMailer classes for testing. After reading the official documentation I see there are two ways to include them in my project:

1) Using composer

2) Copying contents and include paths

I don't know how do use the first option, composer. The second option, copying contents and include paths, looks easier.

I have made a file named test.php with these lines of code:

<?php

        session_start();

        if(isset($_SESSION['username']) and $_SESSION['username'] != ''){

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

            require 'assets/PHPMailer/src/Exception.php';
            require 'assets/PHPMailer/src/PHPMailer.php';
            require 'assets/PHPMailer/src/SMTP.php';

            $mail = new PHPMailer;

            echo 'Versión actual de PHP: ' . phpversion();

        }else{
            ?>
            <br>
        <br>
        <div class="row">
              <div class="text-center">
                  <p class='errorLogin'>Inactive session, relogin <a href="login.php">here</a></p>
              </div>
        </div>
<?php
        }?>

This code only loads the clases into the environment and makes instance of the object PHPMailer class.

After I run it, the log file shows an error:

[Tue Oct 17 10:17:10.331051 2017] [:error] [pid 3879] [client 192.168.0.184:50679] PHP Parse error: syntax error, unexpected 'use' (T_USE) in /var/www/test/sendMail.php

The PHP version: 5.6.30-0+deb8u1

Could anybody help me?


Solution

  • The problem is your use of the use keyword. From the documentation:

    The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped.

    As such, your code should be something like this:

    <?php
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    
    session_start();
    
    if (isset($_SESSION['username']) and $_SESSION['username'] != ''){
      [...]