본문 바로가기

PHP

PHP autoload spl_autoload_register

반응형

PHP 에서 객체지향 형태를 쉽게 지원하기 위해 "__autoload()" function 을 지원한다고 한다.

어떻게 지원하는지 살짝 살펴 보면

<?

$someClass = new SomeClass(); // 이렇게 하면 에러가 난다. 그러니까...

 

===========

 

<?

include some/path/SomeClass.php; //Class 가 정의된 파일을 include(나 require) 한 후에 사용해야 한다.

$someClass = new SomeClass();

 

위처럼 쓰게 되면 매번 include 도 번거롭지만 중첩해서 class를 사용하게 되면 더욱더 혼란스러워지며 유지보수가 힘들어진다.

 

그래서 위에서 언급한 __autoload() 를 사용하여 이런 불편함을 해소 할 수 있다.

동작은 아주 간단하다. 어떻게?

function __autoload() 를 선언하면 된다.

 

<?

function __autoload($className) {

include "some/path" . $className . ".php";

}

 

$someClass = new SomeClass();        //호출하게 되면 __autoload가 불리면서 include를 하게 된다.

 

위와 같은 방식을 보게 되면 뭐랄까.. 이런 방식의 해결책을 언어자체에서 지원해줘야 하는건가.. 하는 생각이 든다.

어쨌든 별 다른 타이핑 및 복잡함 없이 사용할 수는 있다.

 

그런데 PHP 공식 문서를 보면 (언제나 느끼지만 문서가 참.. 불친절하다..) __autoload는 비추한단다. ( http://php.net/manual/en/language.oop5.autoload.php )

그 이유는 spl_autoload_register() 라는게 있는데 이게 더 좋기 때문이라고 한다.

 

그럼 spl_autoload_register 를 알아보자.(SPL이 뭘까 했는데 문서에 Standard PHP Library 의 약자임을 알 수 있다.)

 

spl_autoload_register 도 __autoload 와 비슷하다.

다른 점은 자동로딩시킬 로직을 queue 여러개 등록하여 사용할 수 있다는 것과

몇 가지의 편의 기능이 있다는 정도 같다.

 

자세한 건 공식 문서 ( http://php.net/manual/kr/function.spl-autoload-register.php ) 참조하는게 더 좋을 것 같고,

 

간략하게 아래와 같이 사용할 수 있다.

 

<?

fumction myLoader($className) {

include some . ".php";

 

spl_autoload_register("myLoader");

 

그리고 아래와 같이 좀 더 복잡하게 쓰는것 도 가능하다.

 

<?

fumction firstLoader($className) {

include "first/" . $className . ".php";

 

function secondLoader($className) {

include "second/" . $className . ".php";

}

 

spl_autoload_register("firstLoader");

spl_autoload_register("secondLoader");

 

 

 

 

반응형

'PHP' 카테고리의 다른 글

PHP json encode utf-8 변경  (0) 2016.05.23
PHP 구문 테스트  (0) 2016.05.04