phpoopnamespacesincludemagic-function

Namespace not working with __autoload magic function in php


I have created a class named class_one with namespace MyClassOne as below.

class_one.php

namespace MyClassOne;

class class_one
{
    function __construct()
    {
        echo 'I am from Class One Constructor';
    }
}

And I am trying to use it in index.php file as:

namespace MyClassOne;
require_once('class_one.php');
$one = new class_one();

It's working fine but when I am trying to include with __autoload magic function as:

namespace MyClassOne;
function __autoload($className)
{
    include_once("$className.php");
}

$one = new class_one();

it gives an error:

Fatal error: Uncaught Error: Class 'MyClassOne\class_one' not found in C:\xampp\htdocs\PHP\autoload\index.php:9 Stack trace: #0 {main} thrown in C:\xampp\htdocs\PHP\autoload\index.php on line 9

Please help me where I am doing wrong in this code? Is there a better way to do this?


Solution

  • You're putting a namespace declaration in your program code, which puts the __autoload() function inside that namespace, making it \MyClassOne\__autoload() instead of the desired \__autoload(), so PHP doesn't fire it when trying to load a class.

    Generally, you only want namespace declarations in your class definition files:

    namespace MyClassOne;
    class class_one
    {
    }
    

    Then use use in your program code:

    use MyClassOne\class_one;
    $one = new class_one();
    

    Or use the full class name:

    $one = new \MyClassOne\class_one();
    

    See PSR-4 for details on generally accepted autoloading procedure.