Instantiate class outside namespace

Asked

Viewed 547 times

2

I have a class with the namespace defined:

namespace App;   
class AppSessionHandler {
    private $db;
    //...
    $this->db = Utils::ZendDB();  >>>>>> LINHA 12
}

The following error occurs:

Class 'App Utils' not found in /Class/Utils/class.AppSessionHandler.php on line 12

The class Utils is not included in any namespace.

How to instantiate it within the class AppSessionHandler?

1 answer

3


For being inside the namespace App by instantiating the class Util PHP is looking for the class App\Util, which does not exist. It is necessary to specify that you actually want to use the class Util.

This can be done in two ways:

Import this class using use

<?php

namespace App;

use Utils;

class AppSessionHandler {

    private $db;

    //...

        $this->db = Utils::ZendDB();
}

Or refer to the full class name from the global scope (\):

<?php
namespace App;

class AppSessionHandler {

    private $db;

    //...

        $this->db = \Utils::ZendDB();
}

If you will use the class Util in other class methods, the first method is more efficient. In your example you are importing the class Util, but this could be a class of another namespace as Zend\Db\Connection\Utils. Use the use simplifies the next uses in the class as it will not be necessary to use the full name of the class:

<?php

namespace App;

use Zend\Db\Connection\Utils;

class AppSessionHandler {

    //...

        $this->db = Utils::ZendDB();
}

If using this class only once, the full name from the global \ already resolves. However, it is not so clear at the beginning of the class its dependency on the class Utils

More information on how to work with namespaces you can consult on documentationen.

  • when placing Classname (the bar at the beginning) this indicates what? That there is no namespace?

  • 1

    I just made a correction in your code, it’s not "using" but "use".

  • Filipe, I enriched the answer with a few more details.

  • 1

    After learning this basic for using other Namespaces, Filipe Moraes, watch carefully the PSR-0 and PSR-4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.