Home > database >  How to use "use" from inside a method?
How to use "use" from inside a method?

Time:09-27

I have the following code that works fine

require_once realpath($_SERVER["DOCUMENT_ROOT"].'/../../vendor/autoload.php');
use GeoIp2\Database\Reader;
$reader = new Reader('/var/lib/GeoIP/GeoLite2-City.mmdb');
[...]

class geoIP {
    function __construct($ip) {
        global $reader;
        $record = $reader->city($ip);
    }
}

I want to move the complete namespace GeoIp2 inside the class Foo but it won't let me use use inside the class. How could I do this?

CodePudding user response:

As the PHP manual states, the use keyword must be outside of blocks / function definitions / etc.

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.

If you don't want to use the use keyword, use fully qualified names: new GeoIP2\Database\Reader('/var/...')

CodePudding user response:

Use your constructor to create the object. You should not use global variables in OOP code when possible.

You can add a protected member variable $reader, for instance:

<?php

use GeoIp2\Database\Reader;
[...]

class geoIP {
    protected $reader;

    function __construct($ip) {
        $this->reader = new Reader('/var/lib/GeoIP/GeoLite2-City.mmdb');
        $record = $this->reader->city($ip);
    }
}

Also:

  • Are you sure you need to require all of vendor/autoload.php? This should not be needed.
  • Should your class have a namespace as well?
  •  Tags:  
  • php
  • Related