Fatal error, relating to namespace in php

I am wandering why this below code gives an error:

<?php 

namespace Notebook\Routers{

    function exploder($request_uri){
        $explode = explode("/", $request_uri); 
        return ["count"=> count($explode), "values"=>$explode]; 
    }
}

namespace{
use Notebook\Routers; 
exploder($_SERVER["REQUEST_URI"]);
}

It says Fatal error: Call to undefined function exploder() in /var/www/index.php on line 13

Unless there is something I am missing. The use Notebook\Routers should be able to import the function in the current namespace.

Answers


Just look documentation about aliasing and call your function like this:

Routers\exploder($_SERVER["REQUEST_URI"]);

The 'use' keyword allows you to alias other namespaces within your current namespace. Here you have included a global namespace and the specific class you wanted to use, Routers. To get your code to work, explicitly call out the namespace as I have done below,

namespace Notebook\Routers{

    function exploder($request_uri){
        $explode = explode("/", $request_uri); 
        return ["count"=> count($explode), "values"=>$explode]; 
    }
}

namespace Notebook\Routers{ 
    exploder($_SERVER["REQUEST_URI"]);
}

or, you can use the previous answer's suggestion and use the function

Routers\exploder($_SERVER["REQUEST_URI"])";

When you used the 'use' command for the namespace Notebook\Routers, that namespace was implicitly aliased to Routers. As you are not working with multiple namespaces in the same file, I don't believe using the 'use' keyword is necessary.


Need Your Help

ASP.NET Storing Contextual Data During A Request

asp.net asp.net-mvc-2 httpwebrequest

I am writing an ASP.NET application that initializes some contextual data based on stuff sent through the Request object. How should I be storing this so that it is only visible to objects dealing ...

reading into an enum from xml in c#

c# dynamic enums

I currently have a project I am working on in c# that uses an enum.