Question

I am trying to setup my autoloader as suggested by the top comment in the official PHP documentation

My test environment follows.

C:\www\autoload.php (setup as advised in top comment)

<?php 

spl_autoload_extensions(".php");
spl_autoload_register();

C:\www\Car\Bmw.php

<?php
namespace Car\Bmw;

class Bmw { var $v = 'Hello I am Class : Bmw'; } 

C:\www\Bike\Suzuki.php

<?php
namespace Bike\Suzuki;

class Suzuki { var $v = 'Hello I am Class : Suzuki'; } 

C:\www\index.php

<?php
use Car\Bmw;

include 'autoload.php';

$Obj = new Bmw();
var_dump($Obj);

I have tried some variations such as

  • Defining include path in autoloader with set_include_path('C:\www\');
  • Removing Bmw/Suzuki string from namespace/use or applying in one and not the other

Throughout these trials I have gotten numerous errors such as

Fatal error: Namespace declaration statement has to be the very first statement in the script in C:\www\Car\Bmw.php on line 3

or

Fatal error: spl_autoload(): Class Car\Bmw could not be loaded in C:\www\index.php on line 8

If you are wondering why I want to use this setup please visit the link I gave earlier and read the top comment : Linked again here

Thanks in advance.

Was it helpful?

Solution

You're creating these two classes:

  • Car\Bmw\Bmw
  • Bike\Suzuki\Suzuki

You'll need to modify your namespace declarations to be simply Car and Bike like this:

<?php

namespace Car;

class Bmw { /* */ }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top