Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using namespace in PHP?

Tags:

namespaces

php

Does PHP have some sort of using namespace of C++? (So you don't have to write any namespace before your calls)

I have defined a function within:

namespace \Project\Library {
   function hello() {

    }

}

Another file.php:

use \Project\Library;

hello();     //> Error: Call to undefined function hello()

PS.

I know I could use use \Project\Library as L;

And then do L\hello();

I want to avoid L\ too.

Edit

I answer myself: you cannot do it. And that sucks imo (this is the first thing I don't like of PHP).

Edit2

To be clear: If hello() was a class I could call it directly using use. The problem it is that is a simple function so I have to write its namespace. This is a little mindfucking of PHP.

Maybe we can consider this a bug and open a ticket?

like image 567
dynamic Avatar asked Nov 10 '12 18:11

dynamic


2 Answers

Since PHP 5.3.0 it supports syntax use ... as:

use My\Full\Classname as Another

Also guessing from manual using use directly (without as Another) is not possible (it's not mentioned in manual).

You may be able to use some hack like class factory or workaround via autoloader but simple and direct answer is "it's not possible". :(

like image 64
Vyktor Avatar answered Sep 29 '22 02:09

Vyktor


Even if PHP has namespaces and can declare functions directly outside a class, I would strongly suggest that you, at least, use static class methods. Then you don't have to hack things around and will use namespaces as they were designed to work; with classes.

Here is a working example :

hello.php

<?php

namespace Project\B;

class HelloClass {
    static function hello() {
        echo "Hello from hello.php!";
    }
}

a.php

<?php

namespace Project\A;

require('hello.php');  // still have to require the file, unless you have an autoloader

use \Project\B\HelloClass;   // import this class from this namespace

\Project\B\HelloClass::hello();   // calling it this way render the 'use' keyword obsolete

HelloClass::hello();  // or use it as it is declared

** Note **: use foo as bar; let's you rename the class! For example :

use \Project\B\HelloClass as Foo;   // import this class from this namespace as Foo

Foo::hello();   // calling it this way using the 'use' keyword and alias

** Update **

Interestingly, you can do this :

c.php

namespace Project\C;


function test() {
    echo "Hello from test!\n";
}

a.php

use \Project\C;             // import namespace only
use \Project\C as Bar;      // or rename it into a different local one

C\test();        // works
Bar\test();      // works too!

So, just write use Project\Library as L; and call L\hello();. I think it's your best option here.

like image 41
Yanick Rochon Avatar answered Sep 29 '22 03:09

Yanick Rochon