首页 > 解决方案 > 定义一个包含文件的目录

问题描述

我目前正在从事我的第一个独立项目,我希望将我的代码保持在尽可能好的标准,我一直在查看 PHP 手册,但我似乎缺少如何干净地定义要包含的目录,因为例如我的模板文件夹是“模板/默认”,我想定义一次。

TEMPDIR = templates/default
require_once (__DIR__ . '/TEMPDIR/header.php');

如果有人能指导我正确的方向,将不胜感激,谢谢

标签: php

解决方案


欢迎来到堆栈。

我猜你想定义一个常量TEMPDIR,然后在require_once().

要定义变量,请使用define()(请参阅手册https://secure.php.net/manual/en/language.constants.php):

<?php define('TEMPDIR', 'templates/default');

要在中使用常量,require_once()您必须进行字符串连接(请参阅手册http://php.net/manual/en/language.types.string.php#language.types.string.useful-funcs):

<?php require_once (__DIR__ . '/' . TEMPDIR . '/header.php');

您还应该考虑使用DIRECTORY_SEPARATOR常量来确保您使用适用于任何操作系统的分隔符(请参阅手册http://php.net/manual/en/dir.constants.php):

<?php require_once (__DIR__ . DIRECTORY_SEPARATOR . TEMPDIR . DIRECTORY_SEPARATOR 'header.php');

干杯!


推荐阅读