behz4d
behz4d

Reputation: 1849

PHP Namespaces, the use command

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?

Upvotes: 1

Views: 227

Answers (1)

hassan
hassan

Reputation: 8288

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

Upvotes: 3

Related Questions