Issue with php code: The 'use' keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations

The ‘use’ keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations.

:link: GitHub - ipinfo/php: Official PHP library for IPinfo (IP geolocation and other types of IP data)

User ran the following code from our README:

require_once DIR . '/vendor/autoload.php';

use ipinfo\ipinfo\IPinfo;

$access_token = '5d4a693f2365dc';
$client = new IPinfo($access_token);
$ip_address = '216.239.36.21';
$details = $client->getDetails($ip_address);

$details->city; // Emeryville
$details->loc; // 37.8342,-122.2900

They get the following error when they run the file

"The 'use' keyword must be declared in the outermost scope
of a file (the global scope) or inside namespace declarations."

-supportbot

1 Like

The example in our documentation is designed to be copy-and-pasted into a brand new file: if you’re pasting the example into an existing codebase you may need to make some adjustments. The first 2 lines of the example code import the dependency, you may need to paste these separately at the top of your file, after the opening <?php.

For example, if you have an existing method called getIpAddressCity then you would put the first 2 lines before that method and the IPinfo lookup inside the method:

<?php

require_once __DIR__ . '/vendor/autoload.php';

use ipinfo\ipinfo\IPinfo;

function getIpAddressCity(string $ip) {
  $access_token = '123456789abc';
  $client = new IPinfo($access_token);
  $ip_address = '216.239.36.21';
  $details = $client->getDetails($ip_address);

  return $details->city;
}

echo getIpAddressCity("8.8.8.8");
1 Like