要扩展 Jonathan 的答案,您不必使用 PHP 执行批处理文件。您也可以仅使用 PHP 来生成配置批处理文件。然后,您可以在批处理文件中调用它来访问您需要的所有变量。这非常灵活,并且将变量保存在单独的批处理文件中可以保持主代码干净。
为了说明,您需要三个文件:
-
batch.bat你的主批处理文件
-
setup.php配置生成器
-
config.bat配置批处理文件(setup.php创建)
配置生成器
首先,我们将创建生成config.bat 文件的setup.php 脚本。它可能看起来像这样:
// Create a list of all variable names we want
// to use in the bat file, with their values.
// Note that these can come from anywhere - from
// a database, other files, remote API calls, etc.
$batVariables = array(
'InfoFile' => 'info.txt',
'TrackListing' => 'tracklist.txt',
'AuthorBio' => 'author.txt',
'MainTrack' => 'audio.mp3'
);
// create the code for the configuration
// batch file.
$batCode =
'@echo off'.PHP_EOL.
':: AUTOMATICALLY GENERATED FILE, DO NOT EDIT'.PHP_EOL.
PHP_EOL;
// add all variables
foreach($batVariables as $varName => $value)
{
$batCode .= 'set '.$varName.'='.$value.PHP_EOL;
}
// save the configuration file
file_put_contents('config.bat', $batCode);
这将生成一个如下所示的批处理文件:
@echo off
:: AUTOMATICALLY GENERATED FILE, DO NOT EDIT
set InfoFile=info.txt
set TrackListing=tracklist.txt
set AuthorBio=author.txt
set MainTrack=audio.mp3
加载配置
接下来,在批处理文件中添加这两行(您必须确保 php 可执行文件可在 PATH 系统变量中访问):
:: Generate the configuration batch file
php setup.php
:: Load the configuration with all variables
call config.bat
这将在每次使用主批处理文件时生成一个新的配置。
通过使用call 命令加载config.bat,变量将在主批处理文件的范围内直接可用。这意味着您可以像往常一样开始使用它们,例如:
echo Using the information file %InfoFile%.
除此之外,您可能希望添加一些错误检查,以防无法生成配置文件。一种简单的方法是确保文件存在:
IF EXIST "config.bat" (
call "config.bat"
) ELSE (
echo The configuration file does not exist.
echo.
pause
exit
)