braindump
braindump

Reputation: 309

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 config for all functions in the file in one step?

Thanks.

Upvotes: 2

Views: 549

Answers (5)

mario
mario

Reputation: 145482

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.

Upvotes: 0

Teson
Teson

Reputation: 6736

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

Upvotes: 1

Eric Herlitz
Eric Herlitz

Reputation: 26277

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.

Upvotes: 2

Spyros
Spyros

Reputation: 48636

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.

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318518

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

Upvotes: 1

Related Questions