PHP namespace error?

PHP 5.6

This code:

<?php namespace Database { abstract class Model { } } namespace Models { use Database\Model as DbModel; class Model extends DbModel { } } namespace Models { use Database\Model; class Brand extends Model { } } namespace { $m = new \Models\Model(); } 

causes an error:

"Fatal error: Database \ Model as Model cannot be used because the name is already used in D: \ OpenServer \ domains \ localhost \ index.php on line 23."

This code:

 <?php namespace Models { use Database\Model as DbModel; class Model extends DbModel { } } namespace Models { use Database\Model; class Brand extends Model { } } namespace Database { abstract class Model { } } namespace { $m = new \Models\Model(); } 

has no errors.

Why is this happening? Since the code has not been changed.

+7
php namespaces
source share
2 answers

After several tests: PHP file with several namespaces leads to a difficult understanding, try not to use more than one namespace in one file.

(This is due to binding to non-existing classes when parsing [one file!], Which change the order of PHP parsing, C ++ - things [pointers] - I can’t explain it.)

As the PHP document says: β€œAs a coding practice, it is highly recommended that you combine multiple namespaces into the same file.”

More about the tests I did and the documentation we studied to find out:

http://chat.stackoverflow.com/rooms/71776/discussion-between-axiac-and-jack

+1
source share

The order of your namespace clauses makes a difference here; in the first example, a Database namespace clause is declared before a clause that defines the Models\Model class.

A similar example of this difference can be found in the documentation :

(...) However, the following example causes a fatal error in a name conflict because MyClass is defined in the same file as the use statement.

Individual files or the same file are modeled here by moving the Database namespace lower or higher, respectively.

However, the documentation also states :

As a coding practice, it is highly recommended that you combine multiple namespaces in the same file. The main use case is to combine several PHP scripts into the same file.

Update

Interestingly, this problem is what the Drupal 8 developers recently found out , but according to this, an error report was reported more than two years ago.

A transfer request was sent to solve this problem for the next major version (it can be migrated to 5.x).

+6
source share

All Articles