Instantiate class outside the namespace

2

I have a class with 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 Utils class is not included in any namespace .

How to instantiate it within the class AppSessionHandler ?

    
asked by anonymous 09.06.2015 / 13:08

1 answer

3

Because it is within the namespace App when instantiating the class Util PHP is looking for the App\Util class, which does not exist. You must specify that you actually want to use the Util class.

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 reference the full class name from the global scope ( \ ):

<?php
namespace App;

class AppSessionHandler {

    private $db;

    //...

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

If you are going to use the Util class in other methods of the class, 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 . Using use simplifies the next uses in the class because you will not need to use the full name of the class:

<?php

namespace App;

use Zend\Db\Connection\Utils;

class AppSessionHandler {

    //...

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

If you use 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 with class Utils

More information on working with namespaces can be found in documentation in .

    
09.06.2015 / 13:10