PHP Autoload Class In Hindi

📔 : PHP 🔗

कई developers जब किसी object-oriented applications पर work करते हैं , तो उन्हें Class file को बार बार include करना पड़ता है , और कई बार ज्यादा files होने की वजह से complexity भी बढ़ जाती है। PHP autoloading इस problem को solve करती है।


PHP हमें Classes को automatically load करने का एक efficient method provide करती है , जिसकी help से हमें बिना File के बार बार include किये Classes के साथ work कर सकते हैं।


Class को automatically load करने के लिए predefined function spl_autoload_register() function use किया जाता है। जो एक Callback function accept करता है। जब भी script में कोई class use होती है या first time object बनाया जाता है तो class include हो जाती है।

? PHP 8 से पहले Classes को automatically load करने के लिए __autoload() function का use किया जाता था , लेकिन PHP 8 में इसे remove कर दिया है इसलिए अब spl_autoload_register() function use किया जाता है।

PHP Autoload Class Syntax

spl_autoload_register(function ($class_name) {
    include_once $class_name . '.php';
});

PHP Autoload Class Example

File : MyClass.php

Copy Fullscreen Close Fullscreen
<?php 
        class MyClass{
		static function sayhi(){
			echo 'Hello';
		}
	}
?>

Main File : test.php

Copy Fullscreen Close Fullscreen
<?php 
    /*define function to load class automatically*/
    spl_autoload_register(function($class_name){
    	include_once $class_name.'.php';
    });

    /*call function*/
    MyClass::sayhi();
?>
Output
Hello 

Important
Class को load करने के लिए आपको class के name के according ही file का नाम रखें पड़ेगा। because जब भी class को use किया जाता है , तो spl_autoload_register() function class name ही return करता है।


हालाँकि ये भी हो सकता है कि files किसी दूसरी directory में रखा हो इसके लिए आपको spl_autoload_register() function में include करते समय directory का path देना होगा।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers