Most efficient way to load classes in PHP

10,688

Solution 1

If you're using PHP 5.x, you probably want autoloading.

Solution 2

You don't need to keep using require. You can require_once() which will only parse the file if it has not already been loaded.

Also in PHP, since the includes happen at runtime you are free to require_once() in the middle of a conditional if it is appropriate.

// Only load Class.php if we really need it.
if ($somecondition) {
  // we'll be needing Class.php
  require_once("Class.php");
  $c = new Class();
}
else // we absolutely won't need Class.php

Solution 3

I was C# developer in the past and I can tell you that you need to think bit different if you want to write PHP sites. You need to keep in mind that every unnecessary include will increase extra expenses of resources, and your script will work slower. So think twice before add unnecessary includes.

Back to your question you can use include, require, autoload or even phar. Probably PHAR is more close to C# libraries, you can include one PHAR libraries with a number of classes.

Solution 4

Put this in your config file( or any file included in all pages )

function __autoload($class_name) {
    require_once "Classes" . $class_name . '.php';
}

Put every class in seperate file with its name.
replace "Classes" with your classes folder.

Share:
10,688
Dietpixel
Author by

Dietpixel

Updated on June 04, 2022

Comments

  • Dietpixel
    Dietpixel almost 2 years

    I'm a c# developer, so I'm used to simply compiling a library and including it within a project for use. I haven't really figured out the best way to load different objects within a PHP application. I don't want to keep using require. What is a good approach to take?