Create instance of class dynamically PHP with Namespace

2
$class = ucfirst(strtolower($_GET['type'])) . "Controller";    
include $class . ".php";    
$item = new $class();   

But if I put the class name without being dynamically, for example:

$item = new PessoaController();

It is accepting normally. I would like to know how to solve and why dynamically it says the class does not exist?

    
asked by anonymous 29.04.2014 / 22:28

2 answers

2

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$classitisnotpassingthenamespaceandconsequentlygivesanerrorlikethis:

Namespace declarations at

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 */  }
    
29.04.2014 / 23:07
1

The syntax is correct. Check that the include path is correct if it is still not working add the trim () function in your parse.

$class = trim(ucfirst(strtolower($_GET['type']))) . "Controller";    
include $class . ".php";    
$item = new $class(); 

If it still does not work please post the error here.

    
29.04.2014 / 22:50