Doubt about autoload php

Asked

Viewed 319 times

1

About autoload I studied about:

Autoload for classes in the same folder

function __autoload($nomeClass) {
require_once ("$nomeClass.php");
  }

Autoload for classes in specific folders

spl_autoload_register(function ($nomeClass) {
    if (file_exists("Classes".DIRECTORY_SEPARATOR.$nomeClass.".php") === true) {
        require_once ("Classes".DIRECTORY_SEPARATOR.$nomeClass.".php");
    }
});

How would I make autoload work not just inside the "classes" folder but load any class called in any part of the project, how to do this?

1 answer

1

The ideal is to follow the PHP standards.

PSR-0 It was discontinued, but worth reading

PSR-4 In use

With these recommendations you will learn more about the use of namespace.

Basically the namespace are groupings of classes, interfaces, etc. One of the main objectives is to avoid conflicts. With this you can pass all the way of the class and use the spl_autoload_register to include in your project.

index php.

define("PATH", __DIR__."/vendor/");

/* Namespace + Nome da class */
use Path\Foo\Bar\MyClass;

spl_autoload_register(function($class) {
    $class = str_replace("\\", "/", $class);

    if (file_exists(PATH.$class.".php")) {
        require_once PATH.$class.".php";
    }
});


$cls = new MyClass();
$cls->e();

This way the "spl_autoload_register" will fetch the file /vendor/Path/Foo/Bar/Myclass.php

Myclass.php

<?php

/* Namespace */
namespace Path\Foo\Bar;

/* Nome da classe deve ser o mesmo do arquivo */
class MyClass {
    public function e() {
        echo "OK";
    }
}

However, for a better management of your classes, I recommend the Composer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.