Reputation: 783
I would like to "namespace" a collection of functions and call them. The reason is that I'd like to keep the function names the same across multiple files (and thus distinguish them by namespace). My below implementation yields a "Call to undefined function..." error:
main.php:
//located in /src/main.php
namespace Roles;
use functions\Form; //doesn't seem to work
use functions\View; //doesn't seem to work
use Silex\Application; //works
use Silex\ControllerProviderInterface; //works
class mainfct {
//calls respective functions in the namespaces
Form\a();
Form\b();
View\a();
View\b();
}
form.php:
//located in /src/functions/form.php
namespace Form;
function main() { a(); b();};
function a() {...};
function b() {...};
view.php:
//located in /src/functions/view.php
namespace View;
function main() { a(); b();};
function a() {...not necessarily same code as above...};
function b() {...not necessarily same code...};
The above doesn't seem to work. What's the best way to implement this?
Upvotes: 0
Views: 160
Reputation: 783
Turns out I needed to add require
statements to load the files form.php
and view.php
. Also, I had to "use" the namespaces by use Form;
.
I had to be wary of any references to classes in my namespaces. For example, throw new Exception()
would have to be throw new \Exception()
to be in the right namespace.
Upvotes: 0
Reputation: 166066
It sounds like you're not using PHP 5.6 -- prior to that importing of functions or constants (view use
) was unimplemented in the language.
Re: your update -- unlike the standard included library in languages like ruby or python, PHP namespaces are not tied to the filename/path. You're trying to import functions\Form
use functions\Form; //doesn't seem to work
However, you don't have a namespace named \functions\Form
, you have namespace named \Form
namespace Form;
To get this to work, you'd want to
use Form;
or
namespace functions\Form;
Also, in case its not obvious, for reasons historic and frustrating, PHP namespaces do nothing to include/require/autoload PHP files. That's a separate system in PHP.
Upvotes: 3
Reputation: 46
Namespace is a way to avoid the same name function/class error.
It didn't help you do any include.
You should use include in main.php just like:
include('form.php');
include('view.php');
Or use spl_autoload_register function, see http://php.net/manual/zh/function.spl-autoload-register.php;
Or use psr0 psr4 with composer, see https://getcomposer.org/
Upvotes: 1