使用include时PHP类路径冲突


PHP Class path confliction when using include

我在包含类时遇到问题。这里有一个简单的例子来解释这个问题:

第1类(路径:/home/day/Class_A.php):

class Class_A {
  public function sayHi() {
    echo "Good day";
  }
}

第2类(路径:/home/test/Class_B.php):

class Class_B {
  public function greeting() {
    if(class_exists("Class_A")!=true)
      include "../day/Class_A.php";
    $test = new Class_A();
    $test->sayHi();
  }
}

PHP文件(路径:/home/PHP.PHP)

if(class_exists("Class_B")!=true)
  include "test/Class_B.php";
  $g = new Class_B;
  $g->greeting();

问题是,当php.php包含Class_B并且Class_B包含Class_A时,Class_B无法打开Class_B,因为类的对象的路径现在与php.php文件相同。

我的问题是:有没有一个好的简单的方法来解决这个问题?

尝试更改:

include "../day/Class_A.php";

include dirname(__FILE__) . '/../day/Class_A.php';

这样,您的include将相对于正在执行include的文件(Class_B)。

看起来greeting不是一个静态函数,所以不能执行:

Class_B::greeting();

您必须获得一个类B对象并对其调用greeting,或者将static添加到greetings声明中。

第二,为什么不使用require_one?在php.php 中

require_once('test/ClassB.php');

在ClassB.php:中

require_once('../day/ClassA.php');

使用__autoload,这是一个你定义的神奇函数,它使PHP能够让你知道什么时候没有加载类,但需要加载该类。

If you define the __autoload function like so,
function __autoload ($classname)
{
    require('/path/to/my/classes/'.$classname.'.php');
}
you no longer need to add
require_once('/path/to/my/classes/MyClass.php');
into your files, because the first time that PHP encounters
$mine = new MyClass();
or
MyClass::staticMethodCall();
it will automatically call the __autoload function that you defined earlier.
__autoload('MyClass');

资源:http://blog.samshull.com/2010/02/why-you-should-use-autoload-function-in.html