PHP에서 spl_autoload_register() 함수 사용법에 대한 자세한 설명

墨辰丷
풀어 주다: 2023-03-29 10:22:01
원래의
12998명이 탐색했습니다.

이 글은 주로 PHP에서 spl_autoload_register() 함수의 사용법을 소개하고, __autoload 함수와 spl_autoload_register 함수의 관련 사용법을 예시로 분석합니다. 도움이 필요한 친구들은 참고할 수 있습니다

추천 매뉴얼: php 완성 자습 매뉴얼

이 기능을 이해하기 전에 __autoload라는 또 다른 기능을 살펴보겠습니다.

1. __autoload

이것은 자동 로딩 기능입니다. PHP5에서는 정의되지 않은 클래스를 인스턴스화할 때 이 기능이 실행됩니다. 다음 예를 보세요.

printit.class.php:

<?php
class PRINTIT {
 function doPrint() {
 echo &#39;hello world&#39;;
 }
}
?>
로그인 후 복사

index.php

<?
function __autoload( $class ) {
 $file = $class . &#39;.class.php&#39;;
 if ( is_file($file) ) {
 require_once($file);
 }
}
$obj = new PRINTIT();
$obj->doPrint();?>
로그인 후 복사

index.php를 실행하면 hello world가 정상적으로 출력됩니다. index.php에는 printit.class.php가 포함되어 있지 않기 때문에 printit을 인스턴스화할 때 자동으로 __autoload 함수가 호출되는데, $class 매개변수의 값은 클래스 이름인 printit이다. .

이 방법은 너무 많은 참조 파일을 작성하는 것을 방지하고 전체 시스템을 보다 유연하게 만들 수 있는 객체 지향에서 자주 사용됩니다.

2.spl_autoload_register()

spl_autoload_register()를 다시 살펴보세요. 이 함수는 __autoload와 동일한 효과를 갖습니다. 간단한 예를 살펴보겠습니다.

<?
function loadprint( $class ) {
 $file = $class . &#39;.class.php&#39;;
 if (is_file($file)) {
 require_once($file);
 }
}
spl_autoload_register( &#39;loadprint&#39; );
$obj = new PRINTIT();
$obj->doPrint();?>
로그인 후 복사

__autoload를 loadprint 함수로 바꿉니다. 그러나 loadprint는 __autoload처럼 자동으로 실행되지 않습니다. 이때 spl_autoload_register()는 정의되지 않은 클래스를 발견하면 PHP에 loadprint()를 실행하도록 지시합니다.

spl_autoload_register()는 정적 메소드를 호출합니다.

<?
class test {
 public static function loadprint( $class ) {
 $file = $class . &#39;.class.php&#39;;
 if (is_file($file)) {
  require_once($file);
 }
 }
}
spl_autoload_register( array(&#39;test&#39;,&#39;loadprint&#39;) );
//另一种写法:spl_autoload_register( "test::loadprint" );
$obj = new PRINTIT();
$obj->doPrint();?>
로그인 후 복사

spl_autoload_register

(PHP 5 >= 5.1.2)

spl_autoload_register — __autoload() 함수 등록

설명

bool spl_autoload_register([ 콜백 $autoload_function ] )
SPL __autoload 함수 스택에 함수를 등록하세요. 아직 활성화되지 않은 경우 이 스택의 기능을 활성화합니다.

프로그램에 __autoload 함수가 구현된 경우 __autoload 스택에 명시적으로 등록되어야 합니다. spl_autoload_register() 함수는 Zend 엔진의 __autoload 함수를 spl_autoload() 또는 spl_autoload_call()로 대체하기 때문입니다.

Parameters

autoload_function

등록할 자동 로드 기능입니다. 매개변수가 제공되지 않으면 자동 로드의 기본 구현 함수 spl_autoload()가 자동으로 등록됩니다.

반환 값

성공하면 TRUE를 반환하고, 실패하면 FALSE를 반환합니다.

참고:

SPL은 Standard PHP Library의 약어입니다. 이는 PHP5에 도입된 확장 라이브러리입니다. 주요 기능에는 자동 로드 메커니즘과 다양한 Iterator 인터페이스 또는 클래스의 구현이 포함됩니다. SPL 자동 로드 메커니즘은 자동 로드 기능이 있는 자체 구현 함수에 함수 포인터 autoload_func를 지정하여 구현됩니다.

SPL에는 spl_autoload와 spl_autoload_call이라는 두 가지 다른 기능이 있습니다. autoload_func를 이 두 가지 다른 함수 주소로 지정하여 다양한 자동 로딩 메커니즘을 구현합니다.

classLOAD
{
 staticfunctionloadClass($class_name)
  {
    $filename= $class_name.".class.php";
 $path= "include/".$filename
    if(is_file($path)) returninclude$path;
  }
}
/**
 * 设置对象的自动载入
 * spl_autoload_register — Register given function as __autoload() implementation
 */
spl_autoload_register(array(&#39;LOAD&#39;, &#39;loadClass&#39;));
/**
*__autoload 方法在 spl_autoload_register 后会失效,因为 autoload_func 函数指针已指向 spl_autoload 方法
* 可以通过下面的方法来把 _autoload 方法加入 autoload_functions list
*/
spl_autoload_register( &#39;__autoload&#39;);
로그인 후 복사

spl_autoload_register를 사용하여 클래스 메서드와 __autoload 함수를 동시에 등록한 경우 등록 순서에 따라 처음 등록된 메서드나 함수에 클래스 파일이 로드되면 두 번째 메서드나 함수는 실행되지 않습니다. 등록된 클래스의 메서드 또는 함수입니다. 그렇지 않으면 두 번째로 등록된 클래스의 메서드나 함수가 실행됩니다.

<?php
class autoloader {
  public static $loader;
  public static function init() {
    if (self::$loader == NULL)
      self::$loader = new self ();
    return self::$loader;
  }
  public function __construct() {
    spl_autoload_register ( array ($this, &#39;model&#39; ) );
    spl_autoload_register ( array ($this, &#39;helper&#39; ) );
    spl_autoload_register ( array ($this, &#39;controller&#39; ) );
    spl_autoload_register ( array ($this, &#39;library&#39; ) );
  }
  public function library($class) {
    set_include_path ( get_include_path () . PATH_SEPARATOR . &#39;/lib/&#39; );
    spl_autoload_extensions ( &#39;.library.php&#39; );
    spl_autoload ( $class );
  }
  public function controller($class) {
    $class = preg_replace ( &#39;/_controller$/ui&#39;, &#39;&#39;, $class );
    set_include_path ( get_include_path () . PATH_SEPARATOR . &#39;/controller/&#39; );
    spl_autoload_extensions ( &#39;.controller.php&#39; );
    spl_autoload ( $class );
  }
  public function model($class) {
    $class = preg_replace ( &#39;/_model$/ui&#39;, &#39;&#39;, $class );
    set_include_path ( get_include_path () . PATH_SEPARATOR . &#39;/model/&#39; );
    spl_autoload_extensions ( &#39;.model.php&#39; );
    spl_autoload ( $class );
  }
  public function helper($class) {
    $class = preg_replace ( &#39;/_helper$/ui&#39;, &#39;&#39;, $class );
    set_include_path ( get_include_path () . PATH_SEPARATOR . &#39;/helper/&#39; );
    spl_autoload_extensions ( &#39;.helper.php&#39; );
    spl_autoload ( $class );
  }
}
//call
autoloader::init ();
?>
로그인 후 복사

요약: 위 내용은 이 글의 전체 내용입니다. 모든 분들의 공부에 도움이 되었으면 좋겠습니다.

추천 관련 기사:
1.PHP 자동 로딩 메커니즘 소개 - spl_autoload_register() 함수, PHP 클래스 자동 로딩
2.spl_autoload_register를 사용하여 자동 로딩 예제를 구현하는 방법에 대한 자세한 설명
관련 영상 추천:
1 .Dugu Jiu Cheap(4)_PHP 비디오 튜토리얼

위 내용은 PHP에서 spl_autoload_register() 함수 사용법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!