Php Autoloading Là Gì? Psr

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



You don"t need lớn keep using require. You can require_once() which will only parse the tệp tin if it has not already been loaded.

Bạn đang xem: Php autoloading là gì? psr

Bạn đang xem: How lớn load class files automatically in php

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 & I can tell you that you need lớn think bit different if you want to lớn write PHP sites. You need lớn keep in mind that every unnecessary include will increase extra expenses of resources, and your script will work slower. So think twice before địa chỉ cửa hàng unnecessary includes.

Back to your question you can use include, require, autoload or even phar. Probably PHAR is more close to lớn 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 tệp tin with its name.replace "Classes" with your classes folder.

Xem thêm: Xét Nghiệm Psa Là Gì Và Có Ý Nghĩa Gì Trong Chẩn Đoán Ung Thư Tiền Liệt Tuyến?

You can autoload classes. See:

From that page:

Autoloader, as others mentioned.

If you want khổng lồ 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" & 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 và 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";); Thanks for contributing an answer lớn Stack Overflow!

Please be sure khổng lồ answer the question. Provide details và share your research!

But avoid

Asking for help, clarification, or responding khổng lồ other answers.Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to lớn our terms of service, privacy policy và cookie policy

Not the answer you're looking for? Browse other questions tagged php object loading require or ask your own question.