Question

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.

Was it helpful?

Solution 2

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');

OTHER TIPS

It's __autoload(), not _autoload(). With two underlines in front.

The same goes for your _construct() function.

Note: The PHP manual recommends to use spl_autoload_register() instead of the __autoload() function because it allows more flexibility. Also, the __autoload() function is expected to become deprecated in the future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top