Is it possible to have two classes with the same name if they are in different folders?

I was wondering if something is wrong with two classes with the same name in PHP, if they are in different subfolders, besides the obvious "human factor" of editing the wrong file by mistake?

I searched for other posts related to this, here and elsewhere on the Internet, but I did not find any that could answer this specific question. However, I found that these startup classes from different folders are very useful, and in fact this solved one of my other issues.

+7
source share
7 answers

It is possible to have classes with the same name even in the same folder.

But make sure you load only one class in a PHP script at a time.

They cannot be loaded into the same script at the same time.

PHP does not know if you created two classes with the same name, but the fact that PHP will not load them into the same script. You can use one class at a time.

You can also see namespaces in php.

+8
source

This is the place that namespaces enter. http://www.php.net/manual/en/language.namespaces.rationale.php http://www.php.net/manual/en/language.namespaces.basics.php

This allows you to distinguish between two classes with the same name.

+6
source

Of course, you can create files in one folder or in different folders with the same class names, but you can use only one implementation in one file.

If you really need to give two classes the same name and use them in the same file, the solution can be a namespace ... http://www.php.net/manual/en/language.namespaces.rationale.php

+1
source

I believe that you will have a conflict when you create these classes. Actually, I never tested it, but PHP does not behave like Java, where you can put classes with the same name in different packages and specify the package to distinguish them from the instance ...

0
source

Actually you can, but also think about overloading and about interfaces ...

0
source

The "human factor" is the point.
Not only editing the wrong file error, but working with these classes in the same code would be a complete mess.

0
source

This allows you to have classes with the same name even in the same folder. Here is a sample code.

file name: namespace.php

<?php namespace MyProject { class Connection { public function __construct(){ echo 'My Project class call'; } } function connect() { echo 'My Project connect function.'; } } namespace AnotherProject { class Connection { public function __construct(){ echo 'Another Project class call'; } } function connect() { echo 'Another Project connect function.'; } } ?> 

Another file where we use this namespace. file name: myapp.php

 <?php require 'namespace.php'; //create a class object $obj = new MyProject\Connection; //calling a function MyProject\connect(); //calling a another function AnotherProject\connect(); ?> 
0
source

Source: https://habr.com/ru/post/885815/


All Articles