开发者

PHP "Global" include

Ohai, I'm writing a small PHP application, using a separated config.php file and a functions.php, containing all my custom functions, I'll use in the application. Now, do I really have to include the config.php in every function or is there a way to include the开发者_JAVA百科 config for all functions in the file in one step?

Thanks.


You are bound to use require, require_once, include or include_once when you are to reach methods and classes inside other php files, unless you use some sort of framework.

Try to build a global file which has all includes in it, that way thats the only file you have to include.


The very standard way to do it is include it from your index.php file. Your index.php should include your other pages like :

include 'config.php';
include 'functions.php';
$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'home';

switch($page)
{
    case 'home':           break;
    case 'mail':           break;
    case 'contact':        break;
    default:
        $page = 'home';
}

include("$page.php");

Therefore, at index.php you can include any pages you want.


Create a global.php containing all your require (or include) statements and simply include that file.


convert your functions to methods of a class and you'll never look back.

<?php 
 class MyClass { 
   var $config;     

   function __construct($config) {
     $this->config = $config;
   }

   function myFunc($myArg) {
     return $myArg * $this->config['someSetting'];
   }
}

regards,

/t


You could also use auto_prepend_file in the php.ini for laziness. Or via .htaccess:

php_value auto_prepend_file /home/www/host1235/htdocs/lib/config.php

But that's really an option if your application is coherent, all scripts require that very config file. Otherwise this option needs to be unset again per directory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜