如何有效地包含config.php? [英] How to include config.php efficiently?

查看:72
本文介绍了如何有效地包含config.php?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直对更有效的方式和学习新事物感兴趣.现在,我在每个文件中都使用代码<?php include('config.php'); ?>.根据文件在文件夹结构中的位置,我将使用<?php include('../config.php'); ?>甚至<?php include('../../config.php'); ?>.如何提高效率?有没有一种方法可以让我的config.php拥有根目录,并使根目录中的所有内容都需要config.php?

I'm always interested in more efficient ways and learning new things. Right now, I am using the code <?php include('config.php'); ?> in each and every file. Depending on where the file is in my the folder structure, I would have <?php include('../config.php'); ?> or even <?php include('../../config.php'); ?>. How can I make it more efficient? Is there a way to just have it my config.php in root and make everything in root require config.php?

推荐答案

有一种自动添加文件的方法(auto_prepend_file ini设置),但是您可以做的最大改进是放弃使用多个php文件并将index.php用作整个网站的单个入口点.

there is a way to include a file automatically (auto_prepend_file ini setting), however the biggest improvement you can make is to abandon the usage of multiple php files and use index.php as a single entry point for the whole website.

假设您用页面"questions","tags","users"等编写了一个SO克隆;).在每个页面上,您都需要一些通用的php东西(数据库,会话)和常见的html元素(页眉,页脚) ).一种流行的方法是拥有一堆php文件(questions.php,tags.php,users.php),每个文件都包含常见的内容.例如,users.php将会是这样

suppose you write a SO clone ;) with the pages "questions", "tags", "users", etc. On each page you need some generic php stuff (db, session) + common html elements (header, footer). A popular approach is to have a bunch of php files (questions.php, tags.php, users.php) each of them includes the common stuff. For example, users.php will look like this then

include 'db.php';
include 'session.php';
include 'html.header.php';
.....users-specific stuff 
include 'html.footer.php';

这非常繁琐(您必须重复很多代码)并且不灵活(请向网站上的所有页面添加边栏).我的建议是制作一个由内而外"的文件,即有一个常见的东西"文件,其中包含特定于页面的代码:

This is quite tedious (you have to repeat lots of code) and inflexible (think adding a sidebar to all pages on the site). My suggestion is to make includes "inside out" that is, have a "common stuff" file that includes page-specific code:

 # index.php
 db functions
 session functions
 html header

 $page = isset($_GET['page']) 
   ? preg_replace("/\W+/", "", $_GET['page'])
   : "home";
 include "$page.php";

 html footer

因此,您将在网站上只有一个入口点-这更灵活,而且调试更好.唯一的缺点是网址不太漂亮"(user.php与index.php?page = user),但这可以通过mod_rewrite轻松解决

Thus you'll have a single entry point on the website - this is more flexible and better for debugging. The only drawback is that urls are less "nice" (user.php vs index.php?page=user), but this can be easily solved with mod_rewrite

这篇关于如何有效地包含config.php?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆