php包含文件的方法,在PHP中包含文件的最佳方法?

这取决于你想要完成的目标。

如果你想在文件和它们所在的目录之间建立可配置的映射,你需要设计一个路径抽象并实现一些加载器函数来处理它。我会做一个例子。

假设我们将使用类似Core.Controls.Control的表示法来引用(物理)文件Control.php,该文件将在(逻辑)目录Core.Controls中找到。我们需要做两部分实现:

指示我们的装载机将Core.Controls映射到物理目录/controls。

在该目录中搜索Control.php。

所以这是一个开始:

class Loader {

private static $dirMap = array();

public static function Register($virtual, $physical) {

self::$dirMap[$virtual] = $physical;

}

public static function Include($file) {

$pos = strrpos($file, '.');

if ($pos === false) {

die('Error: expected at least one dot.');

}

$path = substr($file, 0, $pos);

$file = substr($file, $pos + 1);

if (!isset(self::$dirMap[$path])) {

die('Unknown virtual directory: '.$path);

}

include (self::$dirMap[$path].'/'.$file.'.php');

}

}你会像这样使用加载器:

// This will probably be done on application startup.

// We need to use an absolute path here, but this is not hard to get with

// e.g. dirname(_FILE_) from your setup script or some such.

// Hardcoded for the example.

Loader::Register('Core.Controls', '/controls');

// And then at some other point:

Loader::Include('Core.Controls.Control');当然,这个例子是做一些有用的事情的最低限度,但你可以看到它允许你做什么。

抱歉,如果我犯了任何小错误,我就打算这样做。 :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值