Devsway

日々の記録とか記憶とか。

autoloadを使いこなしてイケてるエンジニアになりたいおん



autoloadとは?


いちいちinclude(ファイル)とかしなくてもファイルを自動的に読み込んでくれるやつです。

そうなんだ!すごいね。


__autoload()


すべての始祖。

そしていま現在廃れてゆくもの。。

__から始まるのでマジックメソッドです。

これによりClassを読み込もうとしたときに、「そんなの無いよー」ってときにこのマジックメソッドを実装したロジックでファイルを読み込み試みてくれます。


ちなみに中身はC言語で書かれているらしい。



<?php

// we’ve writen this code where we need

function __autoload($classname) {

$filename = “./”. $classname .”.php”;

include_once($filename);

}


弱点。


保守性が低い。

たくさんの条件でシーケンシャルに読み込みたいときに大変。



そこでspl_autoload_register()ですよ。


autoload()の次世代マシン。

こっちを使いましょう。

基本的にはそんなにかわりません。



function my_autoloader($class) {

include ‘classes/’ . $class . ‘.class.php’;

}


spl_autoload_register(‘my_autoloader’);


これによりたくさん登録してシーケンシャルに処理することが出来ます。




spl_autoload_register(‘first_autoloader’);

spl_autoload_register(‘second_autoloader’);


spl_autoload()


_autoload()のデフォルト実装です。


…イマイチ使いみちわかりません。

spl_autoload(‘Test’);

とかやってたら、もし指定がなかった場合

test.phpを読み込む、、的な。

そりゃそうだろう。



spl_autoload_extensions()


デフォルトの拡張子の設定。

いちいち.phpとかつけなくても良くなる模様。

引数なしでコールした場合は、現在の拡張子一覧をカンマ区切りで返します。


感想とか


まぁぶっちゃけrequrire_once()とかでも代用できるみたい。


これが便利

Extensions doesn’t have to start with a dot, spl_autload() will simply append whatever you supply to the basename. The following example will try to load “test.php” first, and “test/index.php” as well:

まずtest.phpをみて、そのあとtest/index.phpを探すパターン。


spl_autoload_register(‘.php,/index.php’);//なんでここ関数じゃなくていいの?関数と判断してくれてるってこと?

spl_autoload(‘Test’);


追記!!


ああ!勘違いしていた。

spl_autoload ->進化->spl_autoload_register()

と思ってたけど2つの関数は全く別の関係なのか。

多分。



参考


https://stackoverflow.com/questions/7651509/what-is-autoloading-how-do-you-use-spl-autoload-autoload-and-spl-autoload-re




カテゴリー

オレオレIT用語辞典