douhuan1901 2018-04-15 14:03
浏览 56

如何在IF语句中使用Composer自动加载'使用'[重复]

This question already has an answer here:

I am trying to use Composer to auto-load the paths to a firebase/php-jwt library which is located on a different directory as my webpage. Basically, the firebase/php-jwt library is in this path: www/lib/vendor/firebase/php-jwt/src/JWT.php and the page trying to access the library is in this path: www/api/test.php

Here is my code to auto-load paths to library using Composer

if ($count > 0) {
require '../lib/vendor/autoload.php'; // autoload paths to libraries

// Class from firebase/php-jwt library
use \Firebase\JWT\JWT;

// create json-web-token (JWT)
$jwt = JWT::encode($payload, $secret_key);
}

However, I keep getting this error: Parse error: syntax error, unexpected 'use' (T_USE)

How do I solve this?

Edited So I have edited my question. My original question initially did not reflect the code within the 'if' block, but now I have updated my question to reflect that. So the problem was that 'use' must be declared in the outermost scope of a file (the global scope). I writing this down so that people know what the problem initially was. Anyways, thanks to all who tried to help in solving my question.

</div>
  • 写回答

1条回答 默认 最新

  • dsl2014 2018-04-15 15:40
    关注

    So the issue that was causing the error was the 'use' inside the 'if' block. This is because 'use' does the importing at compile time and not runtime, so it cannot be block scoped.

    require '../lib/vendor/autoload.php'; // autoload paths to libraries
    
    // Class from firebase/php-jwt library
    use \Firebase\JWT\JWT;
    
    if ($count > 0) {
         // create json-web-token (JWT)
        $jwt = JWT::encode($payload, $secret_key);
    }
    
    评论

报告相同问题?