[PHP] Question about having multiple files.

Experienced Elementalist
Joined
Jul 4, 2004
Messages
211
Reaction score
0
I am designing a website in PHP atm and i have several different files that use functions from one another, as well as some veriables used in all of them. The current file structure goes as follows:

Index.php - This file just has the theme, and includes "includes.php"
-----Includes.php - This file includes: "functions.php","accounts.php","news.php","db.php", and puts it all togeather ( basically index.php without the theme... ), also this file contains the global veriables needed throughout all of the files, such as $ip ( so i dont have to keep redefining it in each file i use it in ), $debug, etc.
Then we have the files with the functions in them that includes calls:
Functions.php
accounts.php
db.php
news.php


When i stick the veriables needed in all of the files into a config.php file, and include them the veriables dont go into the functions, such as if i have:

PHP:
<?php
include("config.php");

echo $ip; // this will print the IP.

function whatever()
{
      echo $ip; // This will print nothing, its blank, or if i do echo "IP: $ip" or echo "IP: " . $ip; it prints just IP:
}

?>


I was thinking of moving the entire site to OOP and make them all create an instance of class config or extend class config, but i dont know if that will work or not.

Also, if i am to make it OOP, how do i go about doing that?

And finally: does it make a different in the config, for the veriables to carrie over into the functions when included if i make their name:

PHP:
var $ip = $_SERVER['REMOTE_ADDR'];
//compared to
$ip = $_SERVER['REMOTE_ADDR']; // ( how i have it now )

Thanks.
 
variables in a function are local, and they will not interact with variables from elsewhere, what you could do is load the IP into the function by something like this...

PHP:
<?php
include("config.php");

function whatever($ip)
{
      echo $ip;
}

echo $ip; // this will print the IP.

// this too should print the IP

whatever($ip);

?>


edit: also
PHP:
var $variable =
is the same as just writing
PHP:
$variable =
 
Last edited:
variables in a function are local, and they will not interact with variables from elsewhere, what you could do is load the IP into the function by something like this...

PHP:
<?php
include("config.php");

function whatever($ip)
{
      echo $ip;
}

echo $ip; // this will print the IP.

// this too should print the IP

whatever($ip);

?>
edit: also
PHP:
var $variable =
is the same as just writing
PHP:
$variable =

ah cool, didnt think of doing the $ip.

Couldnt i also do ( since the config is included in the file ):

PHP:
<?php
includes("config.php");

function whatever($ip=$ip)
{
   echo $ip;
}
?>

and it would automatically carrie over without me having to fill in $ip when i call the function elsewhere?
 
Alright, i have tryed this out and it does not seam to be working correctly.

I will have it like such:

config.php
PHP:
<?php
$ip=$_SERVER['REMOTE_ADDR'];
//etc.
?>

functions.php
PHP:
<?php
/* includes */
include("config.php");


//I will have a function say... to log something:
function writeLog($ip,etc,etc,etc)
{
//Code here
}

?>

And the $ip veriable will still not carry over into the functions in config.php. Nor will they carry over if i include them in the file that uses functions.php. Nor will things such as login names and passwords for the database, etc, etc.
 
hm, yea it should :/, i have the config.php including in all of the .php files, as well as the .php file that includes them all ( the includes.php that puts it all togeather ).
 
ah, thats what you ment. Yea i was trying to find a way to avoid having to do that for every function that needs something but thats fine. Will do that in a bit ty :)
 
Aargh, you're all a bunch'a n00bs, you know that? :icon6:

PHP:
$var = "Hello world \n";

echo $var; // This will write "Hello world"

function helloworldEcho() {
  global $var;
  echo $var; // This will also write "Hello world"
}

The reason for this is scoped variables. Contrary to languages like C++ and JAVA, PHP does not have variable scope fallback. This means variables are only available in their own scope, unless otherwise defined.

So within a function, you will only have the variables you define therein and 'super globals' - which are server defined variables like $_POST[], $_SERVER[], etc.

There are to my knowladge 3 ways of passing on a variable to a function:

1. By means of a pointer, &variable, the OOP way of doing it. Quite difficult and rarely used in PHP except by the best coders with the biggest projects.
2. By passing on a variable in the function call, function($variable) makes sure the function has the variable available
3. By using globals. You should try to not do this unless you absolutely have to, when for instance a variable is used in -all- functions. If you use too many global variables you'll eventually clutter your global scope so much that your variables have to be named extremely creatively and totally unrecognisable (like $query1, $query2, etc - I have seen this happen, and it aint pretty..).

Personally I usually define 2 global variables: $output[][] (a two-dimensional array thats dynamically filled with all output for a page) and $error. In every function that can fail I use stuff like
PHP:
if(something goes very wrong) 
  $error .= "Something went very wrong! <p>";
This way, you can echo a single variable ($error) at the end of each page and know exactly what went wrong, which is great for troubleshooting :)
 
Last edited:
Aargh, you're all a bunch'a n00bs, you know that? :icon6:

PHP:
$var = "Hello world \n";

echo $var; // This will write "Hello world"

function helloworldEcho() {
  global $var;
  echo $var; // This will also write "Hello world"
}
The reason for this is scoped variables. Contrary to languages like C++ and JAVA, PHP does not have variable scope fallback. This means variables are only available in their own scope, unless otherwise defined.

So within a function, you will only have the variables you define therein and 'super globals' - which are server defined variables like $_POST[], $_SERVER[], etc.

There are to my knowladge 3 ways of passing on a variable to a function:

1. By means of a pointer, &variable, the OOP way of doing it. Quite difficult and rarely used in PHP except by the best coders with the biggest projects.
2. By passing on a variable in the function call, function($variable) makes sure the function has the variable available
3. By using globals. You should try to not do this unless you absolutely have to, when for instance a variable is used in -all- functions. If you use too many global variables you'll eventually clutter your global scope so much that your variables have to be named extremely creatively and totally unrecognisable (like $query1, $query2, etc - I have seen this happen, and it aint pretty..).

Personally I usually define 2 global variables: $output[][] (a two-dimensional array thats dynamically filled with all output for a page) and $error. In every function that can fail I use stuff like
PHP:
if(something goes very wrong) 
  $error .= "Something went very wrong! <p>";
This way, you can echo a single variable ($error) at the end of each page and know exactly what went wrong, which is great for troubleshooting :)

the two-dimensional array could work for my needs, i could have the key ( the first box if i remember correctly is called the key, never was good with names just good with the coding :/ ) as like Settings and then the other box as the setting name and make the array global that was i can just call $output[settings][ip]?
 
This is also useful for links i have found:

I created a link thing in my config.php ( you need to atleast know some PHP to know what it does i think ):

config.php
PHP:
        $set['setting']['default_mode']        ="news";
        $set['setting']['domain']            ="http://domain";
        $set['setting']['index']            ="index.php";
        $set['setting']['home']                =$set['setting']['domain'] . "/" . $set['setting']['index'] . "?mode=" . $set['setting']['default_mode'];

        //Links
        // home
        $set['link'][0]        ="<a href='" . $set['setting']['home'] . "'> Home</a> | ";
        // registering
        $set['link'][1]        ="<a href='" . $set['setting']['domain'] . "/" . $set['setting']['index'] . "?mode=register'> Register</a> | ";
        // services
        $set['link'][2]        ="<a href='" . $set['setting']['domain'] . "/" . $set['setting']['index'] . "?mode=services'> Services</a> | ";
        // testing
        $set['link'][3]        ="<a href='" . $set['setting']['domain'] . "/" . $set['setting']['index'] . "?mode=tests'> Testing </a>";
And then in my includes.php i made a function printLinks():

printLinks() on includes.php
PHP:
function printLinks()
{
    global $set;
    for ($i =0;$i<count($set['link']);$i++)
    {
        echo $set['link'][$i];
    }
}
And it automatically prints out any links i add to that. Hope its useful to some one.
 
It is possible to forward variables to functions, then edit them, then return them, but thats a lot of code thats not really neccesary.

If you have a variable thats used in a LOT of functions and which a lot of functions have to modify, using a global is the most simple way of doing it. Like I said, don't use many, but there are a few occasions when using a global is the way to go.

Example of the other option:

PHP:
$var['setting']['title'] = "Hello world!";
$var = changeTitle($var);
/* $var[setting][title] now has the value "Boo!". */

function changeTitle($var) {
  $var['setting']['title'] = "Boo!";
  return $var;
}

This works, however, once you get more complex functions you will want to give them several parameters, defined in different locations. Eventually you'll end up with something like changeTitle($page, $username, $userlevel, $location, $language, $errors, $var). Thats obviously not very readable, especially not when you have to add all those vars to a lot of different functions. In those cases, its IMHO better to use one or two globals.

Note that the previous is similar to:

PHP:
$var['setting']['title'] = "Hello world!";
changeTitle();

/* $var[setting][title] now has the value "Boo!". */

function changeTitle() {
  global $var;
  $var['setting']['title'] = "Boo!";
}
 
Last edited:
It is possible to forward variables to functions, then edit them, then return them, but thats a lot of code thats not really neccesary.

If you have a variable thats used in a LOT of functions and which a lot of functions have to modify, using a global is the most simple way of doing it. Like I said, don't use many, but there are a few occasions when using a global is the way to go.

Example of the other option:

PHP:
$var['setting']['title'] = "Hello world!";
$var = changeTitle($var);
/* $var[setting][title] now has the value "Boo!". */

function changeTitle($var) {
  $var['setting']['title'] = "Boo!";
  return $var;
}
This works, however, once you get more complex functions you will want to give them several parameters, defined in different locations. Eventually you'll end up with something like changeTitle($page, $username, $userlevel, $location, $language, $errors, $var). Thats obviously not very readable, especially not when you have to add all those vars to a lot of different functions. In those cases, its IMHO better to use one or two globals.

Note that the previous is similar to:

PHP:
$var['setting']['title'] = "Hello world!";
changeTitle();

/* $var[setting][title] now has the value "Boo!". */

function changeTitle() {
  global $var;
  $var['setting']['title'] = "Boo!";
}

Aye, that for the most part is how im using mine, a lot of functions use the veriables im making, so the global is easier for me to do.
 
Back