I am still having trouble with PHP5 Namespaces.
I have a namespace called Project and I am trying to access a class called registry inside of this Project namespace that has a namespace of Library so at the top of the file that is a Project namespace I use this line use Library\Registry;
Registry class is inside the Library Namespace
This should work but it doesn’t, instead the ONLY way to access my registry class inside this Project namespace is to use this
$this->registry = new \Library\Registry;
I want to be able to use this instead…
$this->registry = new Registry;
That was the whole reason of using
use Library\Registry;
at the top of the Project namespace file
Below I have 3 small example scripts in a folder structure like this.
Library/registry.class.php a class in my Library folder
Controller/controller.class.php and class in my Controller directory
Controller/testing.php a test file to run the script.
E:\Library\Registry.class.php file
<?php
namespace Library
{
class Registry
{
function __construct()
{
echo 'Registry.class.php Constructor was ran';
}
}
}
?>
E:\Controller\Controller.class.php file
<?php
use Library\Registry;
namespace Project
{
class Controller
{
public $registry;
function __construct()
{
include('E:\Library\Registry.class.php');
// This is where my trouble is
// to make it work currently I have to use
// $this->registry = new /Library/Registry;
// But I want to be able to use it like below and that is why
// I have the `use Library\Registry;` at the top
$this->registry = new Registry;
}
function show()
{
$this->registry;
echo '<br>Registry was ran inside testcontroller.php<br>';
}
}
}
?>
E:\Controller\testing.php file
<?php
use Project\Controller;
include('testcontroller.php');
$controller = new Controller();
$controller->show();
?>
I get this error…
Fatal error: Class 'Project\Registry' not found in PATH to file
unless I use this below on the controller.class.php file
$this->registry = new \MyLibrary\Registry;
Because in that file at the top I have use Library\Registry; I should be able to access it like this…
$this->registry = new Registry;
Please help me get it where I can use it like that instead
I believe that’s the wrong way round: you’re
useingLibrary\Registryin the global namespace, and then opening theProjectnamespace.Put the
usestatement inside the namespace you want to import it into.