1

I'm just learning about PHP Namespaces and I have a very simple code which is not working and I'm wondering why:

we have n1.php containing one namespace and a function:

<?php
namespace app\cat1;
function echoo(){
    echo "from cat 1";
}
?>

n2.php:

<?php
    namespace app\cat2;
    function echoo(){
        echo "from cat 2";
    }
?>

now in index.php I have included both n1.php and n2.php to use the echoo function:

<?php

require_once('n1.php');
require_once('n2.php');

use app\cat1;
echoo();

?>

As far as I understood the namespacing, the above code should work but it isn't and I don't know why!? I told PHP to use app\cat1; and the called echoo() function but I get:

Fatal error: Call to undefined function echoo() in E:\xampp\htdocs\test\index.php on line 7

Ofcourse I can do this and it's gonna work:

<?php

require_once('n1.php');
require_once('n2.php');

//use app\cat1; <-- this is commented
app\cat1\echoo(); // <-- and now I'm using full path to run the echoo()
?>

the above is working, but now what's the reason we have use in namespacing?


Another thing: how can we put namespaces in multiple files like I did above and also not use include method? I see in Laravel framework files that this is happening. files only have use etc\blah and there is no inclusion and it's working just fine. so how is that happening?

1 Answer 1

3

by default use keyword will import the object under the namespace , you need to define that you are using function

another thing that you need to pass the function name to use so to solve your issue :

use function app\cat1\echoo;

the docs:

// importing a function (PHP 5.6+)
use function My\Full\functionName;

so , in your example -here I'm using grouping name spaces instead of including files as long as most of online IDEs does not support including- :

namespace app\cat1 {
    function echoo(){
        echo "from cat 1";
    }
}

namespace app\cat2 {
    function echoo(){
        echo "from cat 2";
    }
}

namespace {
    use function app\cat2\echoo;
    //  ^^^^^^^^ see this
    echoo();
    // Output : from cat 2
}

live example : https://3v4l.org/TATgp

Sign up to request clarification or add additional context in comments.

2 Comments

how can we separate namespace files and put the in multiple files and also not use include method? is there a way for that? i see this happening in Laravel framework files, it only uses use and there is no include
I updated my question with the new one in the bottom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.