Re: Namcspaces and include()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



You right, Namespaces do not provide you autoimport of your code, like in Python or JS with their import Something from '/src/some/thing' which is just a file path.

Namespaces intended in PHP just to avoid name collisions in class and function names.

At the end of the day (runtime) your PHP code will be assembled in one big file, which will be executed by PHP engine (in simple words).

and you still need to import everything in this chunk of code. So here we use Namespaces to avoid collisions in names from different packages and file.

But wise folks invent autoloading:

https://stackoverflow.com/questions/1830917/how-do-i-use-php-namespaces-with-autoload

https://www.php.net/manual/en/language.oop5.autoload.php

And, of course, composer.

And it becomes a good practice to put php file in folder "App/Http/Controllers/Big.php" with namespace "use App\Http\Controllers"

But in fact there is no strict required to really put files with this namespace in this folder on your filesystem.


28.07.2022 11:11, paulf@xxxxxxxxxxxxxxxxx пишет:
Folks:

I've been coding in PHP for almost two decades, but I've never used
namespaces in my code. Please verify or correct my understanding of how
namespaces work with include() or require().

In order for a namespace declared at the top of a file to actually be
of any use, the code file which defines the namespace originally must
be included somewhere in a file before the namespace declare. That is,

file1.php:
<?php
namespace \something
// some code which is used in other files

file2.php:
<?php
namespace \something
// the code which uses the namespaced code

file3.php:
<?php
include 'file1.php';
// include this before using the namespace code elsewhere

In other words, the fact of declaring a namespace does not pull in that
code from elsewhere. You must do an include() or require() somewhere in
order to actually use the namespaced code.

I know, this sounds like a really dumb newbie question. Mea culpa.

Paul




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux