9

我想知道如果它们位于不同的子文件夹中,那么在 PHP 中有两个具有相同名称的类是否有任何问题,除了错误编辑错误文件的明显“人为因素”?

我已经在网上和其他地方寻找与此相关的其他帖子,但我没有找到任何可以回答这个特定问题的帖子。然而,我确实发现这个 来自不同文件夹的 Autoload 类非常有用,实际上它解决了我的其他问题之一。

4

6 回答 6

10

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.

于 2011-04-13T12:49:40.087 回答
7

这就是命名空间的用武之地。 http://www.php.net/manual/en/language.namespaces.rationale.php http://www.php.net/manual/en/language.namespaces.basics.php

这使您可以区分同名的两个类。

于 2011-04-13T12:52:49.047 回答
1

当然,您可以在同一个文件夹或不同文件夹中创建具有相同类名的文件,但您只能在一个文件中使用一种实现。

如果您确实需要为这两个类提供相同的名称并且必须在一个文件中使用它们,则解决方案可能是命名空间... http://www.php.net/manual/en/language.namespaces.rationale.php

于 2011-04-13T12:53:20.230 回答
1

即使在同一个文件夹中,也可能有同名的类。这是代码示例。

文件名: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.';
}

}
?>

另一个文件,我们使用这个命名空间。文件名: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();
?>
于 2019-07-09T06:15:24.763 回答
-1

事实上你可以,但也要考虑重载和接口......

于 2011-04-13T12:52:31.640 回答
-2

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

于 2011-04-13T12:49:45.640 回答