PHP에서 spl_autoload_register() 함수 사용법에 대한 자세한 설명
이 글은 주로 PHP에서 spl_autoload_register() 함수의 사용법을 소개하고, __autoload 함수와 spl_autoload_register 함수의 관련 사용법을 예시로 분석합니다. 도움이 필요한 친구들은 참고할 수 있습니다
추천 매뉴얼: php 완성 자습 매뉴얼
이 기능을 이해하기 전에 __autoload라는 또 다른 기능을 살펴보겠습니다.
1. __autoload
이것은 자동 로딩 기능입니다. PHP5에서는 정의되지 않은 클래스를 인스턴스화할 때 이 기능이 실행됩니다. 다음 예를 보세요.
printit.class.php:
<?php class PRINTIT { function doPrint() { echo 'hello world'; } } ?>
index.php
<? function __autoload( $class ) { $file = $class . '.class.php'; 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 . '.class.php'; if (is_file($file)) { require_once($file); } } spl_autoload_register( 'loadprint' ); $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 . '.class.php'; if (is_file($file)) { require_once($file); } } } spl_autoload_register( array('test','loadprint') ); //另一种写法: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('LOAD', 'loadClass')); /** *__autoload 方法在 spl_autoload_register 后会失效,因为 autoload_func 函数指针已指向 spl_autoload 方法 * 可以通过下面的方法来把 _autoload 方法加入 autoload_functions list */ spl_autoload_register( '__autoload');
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, 'model' ) ); spl_autoload_register ( array ($this, 'helper' ) ); spl_autoload_register ( array ($this, 'controller' ) ); spl_autoload_register ( array ($this, 'library' ) ); } public function library($class) { set_include_path ( get_include_path () . PATH_SEPARATOR . '/lib/' ); spl_autoload_extensions ( '.library.php' ); spl_autoload ( $class ); } public function controller($class) { $class = preg_replace ( '/_controller$/ui', '', $class ); set_include_path ( get_include_path () . PATH_SEPARATOR . '/controller/' ); spl_autoload_extensions ( '.controller.php' ); spl_autoload ( $class ); } public function model($class) { $class = preg_replace ( '/_model$/ui', '', $class ); set_include_path ( get_include_path () . PATH_SEPARATOR . '/model/' ); spl_autoload_extensions ( '.model.php' ); spl_autoload ( $class ); } public function helper($class) { $class = preg_replace ( '/_helper$/ui', '', $class ); set_include_path ( get_include_path () . PATH_SEPARATOR . '/helper/' ); spl_autoload_extensions ( '.helper.php' ); 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP에서 데이터베이스 작업은 매우 쉽습니다. 이번 장에서는 CRUD(생성, 읽기, 업데이트, 삭제) 작업을 이해하겠습니다.

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

CakePHP에 로그인하는 것은 매우 쉬운 작업입니다. 한 가지 기능만 사용하면 됩니다. cronjob과 같은 백그라운드 프로세스에 대해 오류, 예외, 사용자 활동, 사용자가 취한 조치를 기록할 수 있습니다. CakePHP에 데이터를 기록하는 것은 쉽습니다. log() 함수는 다음과 같습니다.

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는
