Search code examples
phpfileautoloadhtdocs

How I can use the Autoloading in PHP?


hi i learn php now and I test the Autoloading but it don't work. I have two files: start.php and myClass.php. The files I have in the path ./xampp/htdocs and I want If I start start.php use the Autoloading for include the myClass.php and this functions.

here my Code:

start.php

<?php
    function _autoload($classname){
        $filename = "./".$classname.".php";
        include_once($filename);
    }

    $obj = new myClass();
?>

myClass.php

<?php
    class myClass {

        public function _construct(){

            echo "Die Klasse wurde erfolgreich erzeugt";
        }
    }
?>

I get this error:

Fatal error: Class 'myClass' not found in D:\Webserver\xampp\htdocs\start.php on line 7

What I make wrong.


Solution

  • Need to use spl_autoload_register — Register given function as __autoload() implementation

        function _autoload($class) {
                $filename = $classname.".php"; //assumed, your class file and other files are in same directory
                include_once($filename);
        }
    
    
        spl_autoload_register('_autoload');