I am learning and trying to understand the use of namespace and use in PHP. I also use the spl_autoload_register as mention on the php.net documentation. I'm still confusing on using it and get an error.
I have 2 files on my tutorials folder:
php_oop.php
<?php
namespace php_oop;
class php_oop
{
public function __construct($name){
$this->name = $name;
}
public function get(){
return $this->name;
}
}
tutor.php
<?php
spl_autoload_register(function ($class_name) {
var_dump($class_name);
include $class_name . '.php';
// include 'php_oop.php';
});
use php_oop;
$tutor = new php_oop('My Name');
echo $tutor->get();
Output
Warning: The use statement with non-compound name 'php_oop' has no effect in C:\xampp\htdocs\tutorial\oop\tutor.php on line 9 string(7) "php_oop" Fatal error: Class 'php_oop' not found in C:\xampp\htdocs\tutorial\oop\tutor.php on line 11
May I know how to use it correctly?
use isn't like an import. You must use every class you're using, not every namespace. For your example, it would be:
use php_oop\php_oop;
which would import the php_oop class from the php_oop namespace.
See the documentation for importing namespaces for more information and useful tips.
(side effect: The $class_name passed to spl_autoload_register's callback contains the full name of the class including namespace. For your autoloader to load your class properly, you will either need to change your autoloader code or move your php_oop.php file to a folder named php_oop to match the namespace it comes from.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With