Is it possible to have two classes with the same n

2019-01-28 01:42发布

I was wondering if there is anything wrong with having two classes with the same name in PHP if they're in different sub folders?

-- Other than the obvious 'Human Factor' of editing the wrong file by mistake.

@admin: I have looked for other posts relating to this, here and elsewhere on the web, but found none that answered this specific question.

@everyone: I did however find this (php - Autoload classes from different folders) very helpful though, and in fact it solved one of my other questions!

6条回答
SAY GOODBYE
2楼-- · 2019-01-28 01:49

I believe you will have a conflict when you'll instantiate these classes. Actually I've 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 differentiate them upon instantiation...

查看更多
可以哭但决不认输i
3楼-- · 2019-01-28 01:52

In fact you can, but think also about the overloading, and about the interfaces...

查看更多
再贱就再见
4楼-- · 2019-01-28 01:59

That's where namespaces come in. http://www.php.net/manual/en/language.namespaces.rationale.php http://www.php.net/manual/en/language.namespaces.basics.php

This allows you to differentiate between the two classes of the same name.

查看更多
戒情不戒烟
5楼-- · 2019-01-28 02:00

A 'Human Factor' IS the point.
Not only editing wrong file issue but also working with these classes in the same code would be a total mess.

查看更多
一夜七次
6楼-- · 2019-01-28 02:03

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

But Make sure you have loaded only one class in the PHP script at a time.

They can not be loaded in the same script at same time.

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

You can also look at namespaces in php.

查看更多
姐就是有狂的资本
7楼-- · 2019-01-28 02:16

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

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

查看更多
登录 后发表回答