tags:

views:

169

answers:

2

I know the difference between include and require. And I use require in several places in my project.

But here is the thing: I want to include files ONCE and be able to call it's functions from other include files.

In my header.php file, I have the following code:

<?php 
  require_once('include/dal.php');
  require_once('include/bll.php');
  require_once('include/jquery_bll.php');
?>

Now, in my javascript, I'm calling the jquery_bll.php using jQuery.post, and in jquery_bll.php file I have the following code:

$myDB = new DAL();

My problem is that I get the error message "Class 'DAL' not found in (..)\jquery_bll.php".

I recon I get this message because the file is called from a javascript and therefore it outside of the "scope" or something...

So, is there anyway of including the needed files in header.php and not having to worry about including the same files again?

+4  A: 

You need to also put the

  require_once('include/dal.php');
  require_once('include/bll.php');

on top of your jquery_bll.php, or include your complete header file there.

When your JavaScript calls back to jquery_bll.php, this is a separate HTTP request, which will cause PHP to only evaluate that file. As that file does not seem to include your header.php, the require_once statements that make sure the DAL class is loaded are not executed.

Christian Hang
Of course he's right. You've to make sure that these require_once constructs are called on every HTTP request to make sure the file's contents are available.
Philippe Gerber
okay, there was some comment above mine, stateing that Chris is wrong ...
Philippe Gerber
yeah happened to me too, just deleted my comment :-D
David Archer
Ok, thanks guys.
Steven
A: 

When a request is made to jquery_bll.php from the client, it is called as a brand new page. Any includes etc from previous requests are forgotten. So yes, as was suggested you'll have to include the necessary 'includes' again at the top of jquery_bll.php.

EDIT: If you're using PHP5 you could use its autoload feature which you could get to look in your include/ folder if a class is not yet defined

function __autoload($class_name) {
require_once 'include/' . $class_name . '.php';

}

Though you'll have to watch out for uppercase and lowercase and maybe do some processing on dal vs DAL etc

David Archer
hmm.. okey. I was hoping that the included files resided in some memory bank, in the same way as when you include js files in the html header.
Steven
see my edit as a reply
David Archer