Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP namespaces and require

Tags:

namespaces

php

I need to include several files in a main index.php file. I'm working with namespaces.

Can I use include/require and make the files use the same namespace as index.php without specifying the namespaces and use statements in each included file?

like image 614
johnlemon Avatar asked Mar 18 '11 09:03

johnlemon


People also ask

What is the need of namespace in PHP?

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.

How do namespaces work in PHP?

Like C++, PHP Namespaces are the way of encapsulating items so that same names can be reused without name conflicts. It can be seen as an abstract concept in many places. It allows redeclaring the same functions/classes/interfaces/constant functions in the separate namespace without getting the fatal error.

What is difference between use and namespace in PHP?

A namespace is a way of grouping identifiers so that they don't clash. Using a class implies that you can create an instance of that class, not true with namespaces. 2. You can use using-declarations with namespaces, and that's not possible with classes unless you derive from them.

How can use namespace in another file in PHP?

A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword. Add this to your included file as well. namespace my_ns; After that, your code works just fine.


1 Answers

PHP namespaces are scoped at the file level.

If a.php is inside a namespace, and it includes b.php, but b doesn't specify a namespace, it will not adopt the namespace defined in a.

like image 76
Charles Avatar answered Nov 03 '22 02:11

Charles