3

From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally. Meaning if I was to do something like this it would be valid

foo.php

<?php
require_once("bar.php");
?>

bar.php

<?php
print "Hello World!"
?>

running php foo.php will just output "Hello World!"

Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?. And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.

I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)

(Sorry if this has already been asked, I wasn't sure what to search for)

Amit Shah
  • 4,176
  • 2
  • 22
  • 26

4 Answers4

2

It will only include when the method is called, but have you looked at autoloading?

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

1) Only when the method is called.

2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.

SenorAmor
  • 3,351
  • 16
  • 27
  • Re: 2. It's a memory vs performance question (especially when using opcode cache). Loading code on-demand savs memory, but requires more processing and is harder to cache. – Mchl Mar 02 '12 at 23:03
  • Thanks, thats what I needed to know. I hadn't thought about how the cacheing would work before. Thanks. – Amit Shah Mar 03 '12 at 13:05
0

I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..

evan.stoddard
  • 698
  • 1
  • 5
  • 22
0

As others have mentioned, yes, it's included just-in-time.

However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).

Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.

landons
  • 9,502
  • 3
  • 33
  • 46