[UPHPU] require_once vs. class_exists

Rusty Keele rusty.keele at yahoo.com
Fri Apr 18 10:42:12 MDT 2008


Scott Mattocks <scott at crisscott.com> wrote: Rusty Keele wrote:
> Hi,
> 
>   Which is a better approach to use:
>   
>   1. require_once('path/to/class.php');
> 
>   or
> 
>   2. if(!class_exists('path/to/class.php')) require('path/to/class.php');
> 
>   I have been using the first approach in all my files where I need to instantiate a specific class, but I am wondering if the second approach is more efficient?  Are there any benefits to using the second approach - such as less caching of objects - or do these two statements do the same thing?

It depends on which version of PHP you are using. require_once was not 
very efficient in PHP 4 and early versions of PHP 5. I believe it has 
been fixed in later versions of PHP 5.

On a side not, you are passing a file path to class_exists. That is 
incorrect. You should pass the class name.

On another side note, require, include, require_once and include_once 
are language constructs not functions. You don't need the () and some 
would tell you that it is incorrect to add them.

Scott Mattocks


    I am using PHP 5.2.5, and I recently created a new class that will store database login credentials such as hostname, username and password.

    Now I am searching for all the PHP files that have the db credentials in the code and I'm changing them to instantiate an object of my new class and get the credentials from it.

    I am using require_once to make sure the class file is included, but would I be better off to first check and see if the class exists, and if not then require the class file?

    Ultimately, I am trying to decide if there are any advantages to using class_exists rather than require_once.

-Rusty


       
---------------------------------
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.


More information about the UPHPU mailing list