A3 Code Note

11/28/2022

#11 Theme Development | spl_autoload_register | autoloading classes in php

autoloaders とは

loading classes or interfaces automatically
クラスもしくはインターフェイスを自動的にロードしてくれます

spl_autoload_register{}

オートローダーには spl_autoload_register{} というファンクションがあります。
どういうことをしてくれるのかというと

  • Registers any no. of autoloaders
    オートローダーの番号を登録してくれます。
  • Enables classes and interfaces to be automatically loaded if they are currently not defined
    定義されていないクラスやインターフェイスを自動で使用可能にします。

各種作成
my-php/index.php

<?php

// include_once 'includes/Person.php';
// include_once 'includes/Student.php';

spl_autoload_register( function ( $class ) {
    echo $class;
    include 'includes/' . $class . '.php';
} );

new Student();
new Person();

my-php/includes/Student.php

<?php

class Student {
    public function __construct() {
        echo 'Student' . '</br>';
    }
}

my-php/incluldes/Person.php

<?php

class Person {
    public function __construct() {
        echo 'Person' . '</br>';
    }
}