PHP 自动加载对象(以MVC框架替例)
PHP 自动加载对象(以MVC框架为例)
<?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, 在程序使用未声明的类时会自动调用 __autolaod() 函数来加载;
<?php function __autoload($class_name) { @require $class_name . '.php'; } ?>
2.其中 spl_autoload_register() 用来注册一个自动调用的函数, 可以注册多个函数!
3.$iniPath = ini_get('include_path');ini_set('include_path', $iniPath. . $cPath);通过设置环境变量来达到autoload目的,设置包含路径,以后可以直接包含这些目录中的文件,不需要再写详细的路径了。方法三取自php.MVC,使用参照php.MVC文档
<?php /* * $Header: /PHPMVC/phpmvc-base/WEB-INF/classes/phpmvc/utils/ClassPath.php,v 1.4 2006/02/22 07:18:26 who Exp $ * $Revision: 1.4 $ * $Date: 2006/02/22 07:18:26 $ */ class ClassPath { // ----- Depreciated ---------------------------------------------------- // /** * <p>Setup the application class paths (PHP 'include_path') for the included * class files, for the duration of the main script</p> * *<p>Returns the class path string for testing purposes * * @depreciated * @param string The appServerRootDir. eg: 'C:/Www/phpmvc' * @param array An array of sub-application paths,<br> * eg: $subAppPaths[] = 'WEB-INF/classes/example';, ... * @param string The OS [Optional] [UNIX|WINDOWS|MAC|...] if we have * trouble detecting the server OS type. Eg: path errors. * @public * @returns string */ function setClassPath($appServerRootDir='', $subAppPaths='', $osType='') { // Set AppServer root manually for now if($appServerRootDir == '') { echo 'Error: ClassPath :- No php.MVC application root directory specified'; exit; } #$_ENV; // PHP Superglobals !! // Setup the main phpmvc application include() directories here // Note: could be placed in a n xml config file later !! $appDirs = array(); $appDirs[] = ''; // application root directory $appDirs[] = 'lib'; // Add the sub-application paths, if any if(is_array($subAppPaths)) { $appDirs = array_merge($appDirs, $subAppPaths); } // Setup the platform specific path delimiter character $delim = NULL; // path delimiter character. (Windows, Unix, Mac!!) $winDir = NULL; if( (int)phpversion() > 4 ) { // PHP 5 $winDir = $_ENV["windir"]; // See: PHP v.4.1.0 Superglobals } else { // PHP 4 global $HTTP_ENV_VARS; // depreciated- if( array_key_exists("windir", $HTTP_ENV_VARS) ) { $winDir = $HTTP_ENV_VARS["windir"]; // will be replaced with $_ENV } } if($osType != '') { if( eregi("WINDOWS", $osType) ) { $delim = ';'; // Windows } elseif( eregi("UNIX", $osType) ) { $delim = ':'; // Unix } elseif( eregi("MAC", $osType) ) { $delim = ':'; // Mac !!!!! } } if($delim == NULL) { if( eregi("WIN", $winDir) ) { // _ENV["C:\\Win2K"] $delim = ';'; // Windows } else { $delim = ':'; // Unix, Mac !! } } // Get the current working directory $path = $appServerRootDir; // Strip path directories below 'WEB-INF' $pathToWebInf = ereg_replace("WEB-INF.*$", '', $path); // Replace path backslashes with forward slashes // Note: PHP Regular Expressions do not work with backslashes $pathToWebInf = str_replace("\\", "/", $pathToWebInf); // Drop the trailing slash, if one is present $pathToWebInf = ereg_replace("/$", '', $pathToWebInf); // Setup the environment path string $classPath = NULL; foreach($appDirs as $appDir) { $classPath .= $pathToWebInf.'/'.$appDir.$delim; } // Remove trailing delimiter character $classPath = substr($classPath, 0, -1); // Setup the include_path for the duration of the main php.MVC script ini_set('include_path', $classPath); return $classPath; // for testing } // ----- Public Methods ------------------------------------------------- // function getClassPath($appServerRootDir='', $appDirs, $osType='') { // Set AppServer root manually for now if($appServerRootDir == '') { echo 'Error: ClassPath :- No php.MVC application root directory specified'; exit; } #$_ENV; // PHP Superglobals !! // Setup the platform specific path delimiter character $delim = NULL; // path delimiter character. (Windows, Unix, Mac!!) if($osType == '') { // PHP's build in constant "PATH_SEPARATOR" [unix (:) / win (;)] $delim = PATH_SEPARATOR; } else { // It is handy to be able to specift the OS type for testing $delim = ClassPath::getPathDelimiter($osType); } // Get the current working directory $path = $appServerRootDir; // Strip path directories below 'WEB-INF' $pathToWebInf = ereg_replace("WEB-INF.*$", '', $path); // Replace path backslashes with forward slashes // Note: PHP Regular Expressions do not work with backslashes $pathToWebInf = str_replace("\\", "/", $pathToWebInf); // Drop the trailing slash, if one is present $pathToWebInf = ereg_replace("/$", '', $pathToWebInf); // Setup the environment path string $classPath = NULL; $AbsolutePath = False; // Say: "/Some/Unix/Path/" or "D:\Some\Win\Path" foreach($appDirs as $appDir) { // Check if the specified system path is an absolute path. Absolute system // paths start with a "/" on Unix, and "Ch\:" or "Ch/:" on Win 32. // Eg: "/Some/Unix/Path/" or "D:\Some\Win\Path" or "D:/Some/Win/Path". $AbsolutePath = ClassPath::absolutePath($appDir); if($AbsolutePath == True) { $classPath .= $appDir.$delim; } else { $classPath .= $pathToWebInf.'/'.$appDir.$delim; } } // Remove trailing delimiter character $classPath = substr($classPath, 0, -1); return $classPath; // for testing } /** * Concatenate environment path strings * <p> * Returns the two path strings joined with the correct environment * string delimiter for the host operating system. * * @param string The path string * @param string The path string * @param string The operating type [optional] * @public * @returns string */ function concatPaths($path1, $path2, $osType='') { // Setup the platform specific path delimiter character $delim = NULL; // path delimiter character. (Windows, Unix, Mac!!) $delim = ClassPath::getPathDelimiter($osType); $path = $path1 . $delim . $path2; return $path; } // ----- Protected Methods ---------------------------------------------- // /** * Get environment path delimiter. * <p> * Returns the environment string delimiter for the host operating system. * * @param string The operating type [optional] * @protected * @returns string */ function getPathDelimiter($osType='') { // Setup the platform specific path delimiter character $delim = NULL; // path delimiter character. (Windows, Unix, Mac!!) $winDir = NULL; if( (int)phpversion() > 4 ) { // PHP 5 $winDir = $_ENV["windir"]; // See: PHP v.4.1.0 Superglobals } else { // PHP 4 global $HTTP_ENV_VARS; // depreciated- if( array_key_exists("windir", $HTTP_ENV_VARS) ) { $winDir = $HTTP_ENV_VARS["windir"]; // will be replaced with $_ENV } } if($osType != '') { if( eregi("WINDOWS", $osType) ) { $delim = ';'; // Windows } elseif( eregi("UNIX", $osType) ) { $delim = ':'; // Unix } elseif( eregi("MAC", $osType) ) { $delim = ':'; // Mac !!!!! } } if($delim == NULL) { if( eregi("WIN", $winDir) ) { // _ENV["C:\\Win2K"] $delim = ';'; // Windows } else { $delim = ':'; // Unix, Mac !! } } return $delim; } /** * Check if the specified system path is an absolute path. Absolute system * paths start with a "/" on Unix, and "Ch\:" or "Ch/:" on Win 32. * Eg: "/Some/Unix/Path/" or "D:\Some\Win\Path" or "D:/Some/Win/Path". * * Returns True if the suppplied path absolute, otherwise returns False * * @param string The path to check, like: "/Some/Unix/Path/" or * "D:\Some\Win\Path". * @public * @returns boolean */ function absolutePath($systemPath) { // Say: "/Some/Unix/Path/" or "D:\Some\Win\Path" or "D:/Some/Win/Path" $fAbsolutePath = False; // Boolean flag value //"[/]Some/Unix/Path/" if (preg_match("/^\//", $systemPath)) { $fAbsolutePath = True; //"[D:\]Some\Win\Path" // "i" says "ignore case" // Note the extra escape "\" reqd for this to work with PHP !!! } elseif(preg_match("/^[a-z]:\\\/i", $systemPath)) { $fAbsolutePath = True; //"[D:/]Some/Win/Path" } elseif(preg_match("/^[a-z]:\//i", $systemPath)) { $fAbsolutePath = True; } return $fAbsolutePath; } } ?>
?
<?php /* * $Header: oohforms/WEB-INF/ModulePaths.php * $Revision: * $Date: 2003.04.22 * * ==================================================================== * The module paths * * @author John C Wildenauer * @version * @public */ class ModulePaths { /** * Return an array of global paths * * @public * @returns array */ function getModulePaths() { // Setup the main module include() directories here // Note: could be placed in an xml config file later !! $appDirs = array(); $appDirs[] = ''; // starting with the sub-application home directory $appDirs[] = 'login'; $appDirs[] = 'login/classes'; $appDirs[] = 'login/tpl'; $appDirs[] = 'project'; $appDirs[] = 'project/classes'; $appDirs[] = 'project/tpl'; return $appDirs; } } ?>
?调用方法autoloader.php
<?php // Set the application path $moduleRootDir = 'D:/workspace/eh_plat_wms/dev_src'; // no trailing slash // Set the OS Type [Optional] [UNIX|WINDOWS|MAC] if we have // trouble detecting the server OS type. Eg: path errors. $osType = 'WINDOWS'; // Setup application class paths first include 'lib/ClassPath.php'; // Setup the module paths include 'config/ModulePaths.php'; $modulePaths = ModulePaths::getModulePaths(); $mPath = ClassPath::getClassPath($moduleRootDir,$modulePaths, $osType); // Retrieve and merge the php.ini path settings $iniPath = ini_get('include_path'); $cPath = ClassPath::concatPaths($mPath, $iniPath, $osType); echo $cPath; // And set the 'include_path' variables, as used by the file functions ini_set('include_path', $cPath); ?>

핫 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)

뜨거운 주제











Linux 시스템에서 PATH 환경 변수를 설정하는 방법 Linux 시스템에서 PATH 환경 변수는 시스템이 명령줄에서 실행 파일을 검색하는 경로를 지정하는 데 사용됩니다. PATH 환경 변수를 올바르게 설정하면 어느 위치에서나 시스템 명령과 사용자 정의 명령을 실행할 수 있습니다. 이 기사에서는 Linux 시스템에서 PATH 환경 변수를 설정하는 방법을 소개하고 자세한 코드 예제를 제공합니다. 현재 PATH 환경 변수를 봅니다. 현재 PATH 환경 변수를 보려면 터미널에서 다음 명령을 실행합니다. echo$P

기계력 보고서 편집자: 우신(Wu Xin) 국내판 휴머노이드 로봇+대형 모델팀이 옷 접기 등 복잡하고 유연한 재료의 작업 작업을 처음으로 완료했습니다. OpenAI 멀티모달 대형 모델을 접목한 Figure01이 공개되면서 국내 동종업체들의 관련 진전이 주목받고 있다. 바로 어제, 중국의 "1위 휴머노이드 로봇 주식"인 UBTECH는 Baidu Wenxin의 대형 모델과 긴밀하게 통합되어 몇 가지 흥미로운 새로운 기능을 보여주는 휴머노이드 로봇 WalkerS의 첫 번째 데모를 출시했습니다. 이제 Baidu Wenxin의 대형 모델 역량을 활용한 WalkerS의 모습은 이렇습니다. Figure01과 마찬가지로 WalkerS는 움직이지 않고 책상 뒤에 서서 일련의 작업을 완료합니다. 인간의 명령을 따르고 옷을 접을 수 있습니다.

PHP를 사용하여 웹 페이지를 작성할 때 때로는 현재 PHP 파일에 다른 PHP 파일의 코드를 포함해야 할 때가 있습니다. 이때, include 또는 include_once 함수를 사용하여 파일 포함을 구현할 수 있습니다. 그렇다면 include와 include_once의 차이점은 무엇입니까?

경로 환경 변수를 설정하는 방법: 1. Windows 시스템에서 "시스템 속성"을 열고 "속성" 옵션을 클릭한 후 "고급 시스템 설정"을 클릭하고 "시스템 속성" 창에서 "고급" 탭을 선택한 다음 "환경 변수" " 버튼을 클릭하고 "경로"를 찾아 클릭하여 편집하고 저장합니다. 2. Linux 시스템의 경우 터미널을 열고 bash 구성 파일을 열고 끝에 "export PATH=$PATH: 파일 경로"를 추가합니다. 3. MacOS 시스템의 경우 작업은 위와 동일합니다.

"Linux에서 PATH 환경 변수의 역할과 중요성" PATH 환경 변수는 Linux 시스템에서 매우 중요한 환경 변수 중 하나이며 시스템이 실행 가능한 프로그램을 찾는 디렉터리를 정의합니다. Linux 시스템에서는 사용자가 터미널에 명령을 입력하면 시스템이 PATH 환경 변수에 나열된 디렉터리를 하나씩 검색하여 해당 명령의 실행 파일이 있는지 확인하고 실행합니다. 그렇지 않으면 "commandnotfound" 메시지가 표시됩니다. PATH 환경 변수의 역할: 단순화

Linux에서 PATH 환경 변수를 올바르게 설정하는 방법 Linux 운영 체제에서 환경 변수는 시스템 수준 구성 정보를 저장하는 데 사용되는 중요한 메커니즘 중 하나입니다. 그 중 PATH 환경 변수는 시스템이 실행 파일을 검색하는 디렉터리를 지정하는 데 사용됩니다. PATH 환경 변수를 올바르게 설정하는 것은 시스템의 정상적인 작동을 보장하는 핵심 단계입니다. 이 기사에서는 Linux에서 PATH 환경 변수를 올바르게 설정하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. 현재 PATH 환경변수를 확인하고 터미널에 다음 명령어를 입력합니다.

구성 단계: 1. Java 설치 디렉토리를 찾습니다. 2. 시스템 환경 변수 설정을 찾습니다. 3. 환경 변수 창에서 "Path"라는 변수를 찾고 편집 버튼을 클릭합니다. 변수 창에서 "새로 만들기" 버튼을 클릭하고 팝업 대화 상자에 Java 설치 경로를 입력합니다. 5. 입력이 올바른지 확인한 후 "확인" 버튼을 클릭합니다.

1. jdk 설치 디렉터리 아래의 bin 디렉터리를 찾아 복사합니다. 2. 컴퓨터를 클릭하고 속성을 선택합니다. 3. 고급, 환경 변수를 선택합니다. 4. 경로 줄에 영어 반자 기호(;)를 붙여넣습니다. 결국, 관리자 사용자 변수는 관리자만 사용 가능하며, 시스템 변수는 모든 사용자가 사용할 수 있습니다. 환경변수 중 path는 해당 경로 아래에서 java 명령이 실행되도록 하기 위해 사용되는 것으로, 환경변수 설정에 있어서 없어서는 안 될 링크라고 할 수 있다.
