If you have a class inside a namespace it should be declared together !!!
Example:
<?php namespace Controller {
class CarroController {
public function __construct()
{
echo "PHP";
}
}
}
Solution
<?php
$class = ucfirst(strtolower($_GET['type'])) . "Controller";
include $class . ".php";
$namespaceClass = "\Controller\".$class;
$item = new $namespaceClass;
or (with Reflection )
<?php
$class = ucfirst(strtolower($_GET['type'])) . "Controller";
include $class . ".php";
$namespaceClass = "\Controller\".$class;
$item = new ReflectionClass($namespaceClass);
$ins = $item->newInstance();
Result
WhytheError?
Ifyouuse$item=new$class
itisnotpassingthenamespaceandconsequentlygivesanerrorlikethis:
Namespace declarations at php
Defining a namespace in a file
Reference
<?php namespace Exemplo1;
class Connection { /* code */ }
function Open() { /* code */ }
Defining multiple namespace in file
Reference
<?php
namespace Exemplo1 {
class Connection { /* code */ }
function Open() { /* code */ }
}
namespace Exemplo2 {
const Value = 1;
class Db { /* code */ }
function Close() { /* code */ }
}
namespace { // código global
session_start();
function DateTime(){ /* code */ }
}
Defining namespace with hierarchy
Reference
<?php namespace Code\Connection\Db;
class Connection { /* code */ }
function Open() { /* code */ }