I am learning how to use namespaces and autoload in PHP today, and I seem to be in the checkpoint. Everything seems to work when I don't use spl_autoload_register , but require_once instead.
The structure of my folder is minimal:
- index.php - class/ - Users.php
In my index.php file, I have:
<?php require_once('class/Users.php'); echo User::get(1);
In my class/Users.php file, I have:
<?php Class User { function get($id) { return $id; } }
and this works absolutely fine, returning id 1
Ideally, I want to use the autoload function, and I discovered spl_autoload_* , and this is what I tried to do, but without success:
In my class/Users.php file, I have:
<?php namespace Users;
In my index.php file, I have:
<?php // Changed to using spl_autoload_register using an anonymous function to load the class spl_autoload_register(function($class){ include('class/' . $class . '.php'); }); echo Users\User::get(1); // Added the Users namespace
but I get an error:
`Class 'Users\User' not found in /Applications/MAMP/htdocs/index.php on line 7`
Not sure what I'm doing wrong.