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ヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









Linux システムで PATH 環境変数を設定する方法 Linux システムでは、PATH 環境変数を使用して、システムがコマンド ラインで実行可能ファイルを検索するパスを指定します。 PATH 環境変数を正しく設定すると、任意の場所でシステム コマンドやカスタム コマンドを実行できるようになります。この記事では、Linux システムで PATH 環境変数を設定する方法と詳細なコード例を紹介します。現在の PATH 環境変数を表示する ターミナルで次のコマンドを実行して、現在の PATH 環境変数を表示します: echo$P

Machine Power Report 編集者: Wu Xin 国内版の人型ロボット + 大型模型チームは、衣服を折りたたむなどの複雑で柔軟な素材の操作タスクを初めて完了しました。 OpenAIのマルチモーダル大規模モデルを統合したFigure01の公開により、国内同業者の関連動向が注目を集めている。つい昨日、中国の「ヒューマノイドロボットのナンバーワン株」であるUBTECHは、Baidu Wenxinの大型モデルと深く統合されたヒューマノイドロボットWalkerSの最初のデモを公開し、いくつかの興味深い新機能を示した。 Baidu Wenxin の大規模モデル機能の恩恵を受けた WalkerS は次のようになります。 Figure01 と同様に、WalkerS は動き回るのではなく、机の後ろに立って一連のタスクを完了します。人間の命令に従って服をたたむことができる

PHP を使用して Web ページを作成する場合、他の PHP ファイルのコードを現在の PHP ファイルに含める必要がある場合があります。現時点では、include 関数または include_once 関数を使用してファイルのインクルードを実装できます。では、include と include_once の違いは何でしょうか?

パス環境変数を設定する方法: 1. Windows システムでは、[システムのプロパティ] を開き、[プロパティ] オプションをクリックし、[システムの詳細設定] をクリックし、[システムのプロパティ] ウィンドウで [詳細] タブを選択します。 「環境変数」ボタンをクリックし、「パス」を見つけてクリックして編集し、保存します。 2. Linux システムの場合は、ターミナルを開き、bash 構成ファイルを開き、ファイルの最後に「export PATH=$PATH: file path」を追加します。ファイルを保存して保存します; 3. MacOS システムの場合、操作は上記と同じです。

「Linux における PATH 環境変数の役割と重要性」 PATH 環境変数は、Linux システムの非常に重要な環境変数の 1 つで、システムが実行可能プログラムを検索するディレクトリを定義します。 Linuxシステムでは、ユーザーがターミナルにコマンドを入力すると、環境変数PATHに設定されているディレクトリを1つずつ検索し、コマンドの実行ファイルが存在するかどうかを確認し、見つかった場合は実行します。それ以外の場合は、「commandnotfound」というプロンプトが表示されます。 PATH 環境変数の役割: 簡略化

Linux で PATH 環境変数を正しく設定する方法 Linux オペレーティング システムでは、環境変数はシステム レベルの構成情報を保存するために使用される重要なメカニズムの 1 つです。このうち、PATH 環境変数は、システムが実行可能ファイルを検索するディレクトリを指定するために使用されます。 PATH 環境変数を正しく設定することは、システムの正常な動作を保証するための重要な手順です。この記事では、Linux で PATH 環境変数を正しく設定する方法と、具体的なコード例を紹介します。 1. 現在の PATH 環境変数を確認し、ターミナルに次のコマンドを入力します。

設定手順: 1. Java インストール ディレクトリを見つけます; 2. システム環境変数設定を見つけます; 3. 環境変数ウィンドウで「Path」という名前の変数を見つけて編集ボタンをクリックします; 4. ポップアップ編集環境で変数ウィンドウで、「新規」ボタンをクリックし、ポップアップダイアログボックスに Java のインストールパスを入力します; 5. 入力が正しいことを確認した後、「OK」ボタンをクリックします。

1. jdk インストール ディレクトリの下にある bin ディレクトリを見つけてコピーします 2. [コンピュータ] をクリックして [プロパティ] を選択します; 3. [詳細設定]、[環境変数] を選択します; 4. パス行に貼り付けます。管理者ユーザー変数は管理者ユーザーのみが使用できますが、システム変数はすべてのユーザーが使用できます。環境変数の中でもパスはjavaコマンドが確実にパス配下で実行されるようにするために使用され、環境変数設定には欠かせないリンクと言えます。
