What Is Autoload in PHP

What is autoload in php?

This will be of help to you about usage of autoload. http://ditio.net/2008/11/13/php-autoload-best-practices/

It's a magic function that helps you include / require files using class name.

function __autoload($class_name) 
{
require_once $DOCUMENT_ROOT . “/classes/” . $class_name .“.php”;
}

It's deprecated at PHP 7.2.0 and spl_autoload_register is recommended for that purpose.

how does php autoloader works

The PHP autoloader is just a mechanism to include a file when a class is constructed.

If you put all your classes in 1 file, you dont need an autoloader. Of course, when programming OO you give every class its own file, and that's where the autoloader comes in.

Some examples:

class AutoLoader
{
public function __construct()
{
spl_autoload_register( array( $this, 'ClassLoader' ));
}

public function ClassLoader( $class )
{
if( class_exists( $class, false ))
return true;

if( is_readable( 'path_to_my_classes/' . $class . '.php' ))
include_once 'path_to_my_classes/' . $class . '.php'
}
}

$autoloader = new AutoLoader();

What happens here is that when the autoloader class is created, the class method Classloader is registered as a autoloader.

When a new class is created, the Classloader method first checks if the file for the class is already loaded. If not, the class is prepended with a path and extended with an extension. If the file is readable, it is included.

Of course, you can make this very sophisticated. Let's look at an example with namespaces and a mapper. Assume we are in the autoloader class:

  private $mapper array( 'Foo' => 'path_to_foo_files/', 'Bar' => 'path_to_bar_files/');

public function ClassLoader( $class )
{
if( class_exists( $class, false ))
return true;

// break into single namespace and class name
$classparts = explode( '\\', $class );
$path = $this->mapper[$classparts[0]];

if( is_readable( $path . $classparts[1] . '.php' ))
include_once $path . $classparts[1] . '.php'
}

Here, the classname is split in the namespace part and the classname parts. The namespace part is looked up in a mapper array and that path is then used as include path for the php file.

These are just examples to demonstrate what can be done with autoloader. For production there is some more work to be done, error checking for example.

How to check if Autoload loads only used classes?

With this code, the first time you refer to any class, it will load every class. This will work, but almost certainly isn't what you want. In an autoloader, you usually just want to load only the one source file containing the one class referenced by $class_name. Something like this:

spl_autoload_register(function ($class_name) {
$filename = '/path/to/classes/' . $class_name . '.php';
require_once $filename;
});

This obviously becomes very difficult if your source file names don't match your class names or you otherwise can't determine the source file names based on the class names. This is why you should use PSR-4 naming conventions.

Is it bad to use autoloading in PHP?

Bad? No. __autoload() is one of my favorite additions to PHP 5. It removes the responsibility (and annoyance) of manually having to include/require the class files necessary to your application. That being said, it's up to you as the developer to ensure that only the 'appropriate classes' are loaded. This is easily done with a structured naming scheme and directory structure. There are plenty examples online of how to properly use __autoload(), do a Google search and you'll find plenty of information.

PHP's use Keyword and Autoloading

1) The class is autoloaded when you perform a new Class() statement.

2) see 1)

3) Which pattern is best to follow and why?:

I'd recommend to use use because you might get into a situation where you have really long namespaces and your code will become unreadable.

From the php docs:

This example attempts to load the classes MyClass1 and MyClass2 from
the files MyClass1.php and MyClass2.php respectively.

<?php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});

$obj = new MyClass1();
$obj2 = new MyClass2();
?>

Namespaces are only an additional feature to organize classes.

EDIT: As @IMSoP pointed out in the comments, new is not the only time the autoloader is triggered. Accessing a class constant, static method, or static property will also trigger it, as will running class_exists.

Do you really need to Auto-load ALL pages of a Class-based site on every pageload?

That's a confusing name for the file, as autoloading is a mechanism in PHP that allows you to load classes as and when they are needed, a good solution when you have many classes and only a few will be needed for each execution.

For example:

function autoload($class_name) {
$file = "classes/$class_name.php";

// You could add some checks here (e.g. whether the file exists, whether the
// class indeed exists after the file is loaded) to facilitate better errors,
// of course this would marginally increase the time needed to load each class.

require $file;
}

// Register the `autoload` function with PHP's autoload mechanism
spl_autoload_register('autoload');

// This will execute `autoload('Class')` (unless `Class` is already defined)
$instance = new Class;

So, to answer your questions:

  1. It is not necessary to load them all, however classes that are used must be available, either by loading them all together (current situation), loading them conditionally (if(p == 'whatever') require 'classes/whatever.php'), or by using autoloading.

  2. There is some delay whenever a file is included as the file must be parsed/executed. PHP is fairly fast but still, including files you do not need is a waste. If you're using bytecode caching, the retrieved bytecode must still be executed.

  3. That is one avenue of improvement, autoloading presents a more dynamic alternative.

  4. Dependencies may be a problem if any of your page classes depend on another class, as your conditional loading could get very bloated.

Also a little additional material regarding bytecode caching, if you're using it:

  • PHP5 Frameworks: Autoloading and Opcode Caching
  • Do PHP opcode cache work with __autoload?

The summary seems to be that, as long as you use include or require to load the file, bytecode caching will work as intended.

PHP - Autoload only needed classes

All registered autoloader functions will be called when you try to instantiate a new class or until it finally loads the class or throws an error. The way you have it now, you're registering the same autoloader function again and again for each directory, and file.

What you'd want to do is something along the lines of this.

namespace autoloader;

class autoloader
{
public function __construct()
{
spl_autoload_register([$this, 'autoload']);
}

public function autoload($classname)
{
if (! file_exists("{$classname}.class.php")) {
return;
}

include_once "{$classname}.class.php";
}
}

new autoloader();

Every autoloader function gets the class FQCN passed into it, and from there you'll have to parse it and figure out if you can load the file where that class exists. For instance, if I do the following.

use Some\Awesome\ClassFile;

$class = new ClassFile();

The autoloader we've registered will get the string Some\Awesome\ClassFile passed in as an argument, which we can then parse and see if we have a file for that class, if we don't we return out of the function and let the next registered autoloader function try and find the class.

You can read more about autoloaders in the documentation, I also wrote a blog post about it like 2 months ago that might interest you.

PHP: Is AutoLoader able to load multiple class in a single php file?

You would have to have some complex function to autoload those classes from the file named Client.php. The idea is to translate your namespace\classname into a directory\filename.php

In this instance you would need to name your file A.php then when you call new Protobuf\A() it will find it. Otherwise you will have to create an overly-complex autoloader.

Let's say you do create the autoloader so it finds the A class, then you can have B on the same file, but only if you have already autoloaded A otherwise you have to make some algorythm to know that A and B are on the same page.

I would do the above pattern or the pattern adopted by apps like Magento that turn class names into directory paths by replacing underscores:

$class = new Core_Classes_MyClass_Client();

Your autoloader would replace the underscores and will load:

Core/Classes/MyClass/Client.php //or similar scheme

This to me is an easy way to do it, but I prefer using namespace and class. The above method is not in favor at the moment and from a naming standpoint, very easy to get mixed up since a lot of classes may be in the same folder or nested really deep into sub folders. You could get some really long naming for classes.

How to call __autoload() in php code

You don't call __autoload() yourself, PHP does when it is trying to find the implementation of a class.

For example...

function __autoload($className) {
include $className . '.php';
}

$customClass = new CustomClass;

...this will call __autoload(), passing CustomClass as an argument. This (stupid for example's sake) __autoload() implementation will then attempt to include a file by tacking the php extension on the end.

As an aside, you should use spl_autoload_register() instead. You can then have multiple implementations, useful when using multiple libraries with auto loaders.

...using __autoload() is discouraged and may be deprecated or removed in the future.

Source.

Class not found with composer autoload in different servers

Path to your file is src/content/test/Sandbox.php and according to PSR-4 it should be src/Content/Test/Sandbox.php - on Windows it does not matter, but on Linux it does.



Related Topics



Leave a reply



Submit