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

风格不统一 提交于 2019-11-29 13:44:00

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.

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.

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

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...

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

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.

This is possible to have classes with the same name even in the same folder. Here is the sample of 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();
?>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!