Error 'use' (T_USE) when using autoload

4

I have the following folder and file structure:

-api
  -v1
  -libs
    -Slim
    -Facebook
      -autoload.php
  -index.php
  -login.php

Inside the "index.php" I include the "login.php" include:

require_once 'login.php';

In the "login.php" file I include the "libs / Facebook / autoload.php" file and then I try to use a class:

require_once 'libs/Facebook/autoload.php';
use Facebook\FacebookSession;

The following error is returned:

  

Parse error: syntax error, unexpected 'use' (T_USE)

"autoload.php" contains the following code:

spl_autoload_register(function ($class){
   $prefix = 'Facebook\';
   $base_dir = __DIR__;
   $len = strlen($prefix);
   if (strncmp($prefix, $class, $len) !== 0) {
      return;
   }
   $relative_class = substr($class, $len);
   $file = $base_dir . str_replace('\', '/', $relative_class) . '.php';
   if (file_exists($file)) {
      require $file;
   }
});

What am I doing wrong for autoload not working correctly?

    
asked by anonymous 17.02.2015 / 19:54

1 answer

6

According to this response from SOen :

This is because you probably defined the namespace within a method or function, read about PHP: Using Namespaces :

  

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

To resolve you should move the use out of any function or class.

Assuming it looks like this:

function initiate () {
    require_once 'libs/Facebook/autoload.php';
    use Facebook\FacebookSession;
    ...
}

Do this:

require_once 'libs/Facebook/autoload.php';
use Facebook\FacebookSession;

function initiate () {
    ...
}
    
17.02.2015 / 20:05