-1

IF i include a file into another file. i.e foo.php contains the class "foo", with several methods. At what point does php load the classes into memory, on the include or on the class initiation.

here: include ('foo.php');

or here: $foo = new foo();

For example: If i were to include 50 files that all contain unique classes but only call 1 of those classes what would happen in terms of memory usage? speed? overall - please explain the badness of that action.

Gordon
  • 312,688
  • 75
  • 539
  • 559

1 Answers1

2

When you include a file, all that PHP does is parse that file, and irrespective of whether it contains a class definition, procedural lines, or entirely commented out code, it includes those lines into the current file you have, and then evaluates them. In other words, looks for syntax errors, if the lines are executable - executes them. If you have 50 class files all "included", once the include process is complete, it becomes similar to if you had a single file with all 50 classes defined in it. The behavior for instantiating a single class or multiple classes, then becomes the same. The only difference in overhead would come for the individual evaluation, and inclusion of those 50 files.

If you do have a use case of lots of files with different classes, and only need to include them based on the ones that you might load, check out the autoload functionality in PHP:

<?php
function __autoload($class_name) {
    include $class_name . '.php';
}

$first = new FirstClass();
$second = new SecondClass(); 
?>

http://php.net/manual/en/language.oop5.autoload.php

raidenace
  • 12,789
  • 1
  • 32
  • 35
  • The overhead would be limited if you specified what files needed to be included and limited to just them. Thank you, that makes sense. – wickedbadawesome Sep 05 '12 at 18:20
  • Yes, and also PHP provides special autoload functionality for including class based files for initialization. – raidenace Sep 05 '12 at 18:27