开发者

Most efficient way to load classes in PHP

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 开发者_JAVA百科load different objects within a PHP application. I don't want to keep using require. What is a good approach to take?


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


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


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.


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.


You can autoload classes. See:

  • http://us3.php.net/autoload

From that page:

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

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

Note that you can use spl_autoload_register() if you don't want to use the single magic __autoload function.


The autoloader will solve all your problems.


Autoloader, as others mentioned.

If you want to go step further... look at the way how Kohana (for example) solved the problem.


This question is the first Stack Overflow result from searching "php how to load classes" and other answers which provide examples for autoloading suggest the use of __autoload(). Please note that use of __autoload() is deprecated as of PHP 7.2 and its use is discouraged. Using spl_autoload_register is suggested instead.

The example snippet below is from the documentation page:


spl_autoload_register(function ($class_name) {

    include 'classes/' . $class_name . '.php';

});

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜