PDA

View Full Version : PHP Using "include" twice



IQAndreas
January 17th, 2010, 07:54 AM
I can't seem to get this right. It keeps messing up for me.

I have a PHP file that contains nothing but a "defined or die" and a class definition. I need to use this same class in two different places.

If I use "include" in both places, PHP doesn't display an error, but it just gives me that "no formatting" look and doesn't display everything.

Is there any way to check if a class has already been imported, or any way to allow you to import the same class twice without errors?

Voetsjoeba
January 17th, 2010, 08:15 AM
Yes there is: http://www.php.net/manual/en/function.include-once.php and http://www.php.net/manual/en/function.require-once.php

IQAndreas
January 17th, 2010, 09:07 AM
Ah. I misunderstood that function.

I thought it meant "Include this file only once. If it has been included before, throw an error."

So, let's say I have a PHP page with mixed information, such as this:

List of users:
<?php
foreach(UserDatabase::getUsers() as $user)
{
echo $user->name;
}

class UserDatabase
{
public static function getUsers()
{ return $db->getUsers("WHERE status!='admin'"); }
}
?>
Yes, I know I could write this class differently, but this is the slimmed down version.

How would I be able to include this page twice so each instance believes it is the only one and has never been accessed before?

simplistik
January 17th, 2010, 10:39 AM
just check if the class exists already


if ( !class_exists(UserDatabase) ) include 'foo.php';


http://php.net/manual/en/function.class-exists.php

Voetsjoeba
January 17th, 2010, 11:22 AM
You really shouldn't be mixing class definitions and their usage in the same file like that. Instead, define each class in its own file and include it whenever you need to use it. A class definition should be a standalone unit of definition that can be included anywhere; adding stuff to it that uses the class forces that functionality upon all other pages where you might want to use it.



How would I be able to include this page twice so each instance believes it is the only one and has never been accessed before?

I'm not sure if I understand what you mean; do you want whatever code you put in the include to run every time it is included as if it were included for the first time, but the duplicate class definition is giving you trouble? In that case, I misunderstood you and include_once will do exactly the opposite. However, the solution to your problem is exactly the above - remove the class definition from the include and, within your include, replace it with an include_once of your separate class file. That way, you can include your file as much as you want but still have the class definition included only once.