有没有办法在PHP中使用*.properties文件,就像在Java中一样?我想在属性或XML文件中存储一些应用程序级常量,并在我的代码中轻松调用它们.非常感谢您的指导.谢谢.
cee*_*yoz 17
PHP可以使用本机加载和解析.ini文件parse_ini_file().
您还可以使用包含文件设置常量define().
如果您设置了XML,请查看PHP的XML功能.最简单的解决方案可能是使用SimpleXML.
您还可以使用包含数组的PHP文件来存储数据.例:
config.php文件
<?php 
return array(
    'dbhost' => 'localhost',
    'title'   => 'My app'
);
Run Code Online (Sandbox Code Playgroud)
然后在另一个文件中:
$config = require 'config.php':
echo $config['title'];
Run Code Online (Sandbox Code Playgroud)
        parse_ini_file与*.propertiesJava环境中的文件无关.
我创建了这个函数,它与Java中的等价函数完全相同:
function parse_properties($txtProperties) {
    $result = array();
    $lines = split("\n", $txtProperties);
    $key = "";
    $isWaitingOtherLine = false;
    foreach($lines as $i=>$line) {
        if(empty($line) || (!$isWaitingOtherLine && strpos($line,"#") === 0)) continue;
        if(!$isWaitingOtherLine) {
            $key = substr($line,0,strpos($line,'='));
            $value = substr($line,strpos($line,'=') + 1, strlen($line));
        } else {
            $value .= $line;
        }
        /* Check if ends with single '\' */
        if(strrpos($value,"\\") === strlen($value)-strlen("\\")) {
            $value = substr($value, 0, strlen($value)-1)."\n";
            $isWaitingOtherLine = true;
        } else {
            $isWaitingOtherLine = false;
        }
        $result[$key] = $value;
        unset($lines[$i]);
    }
    return $result;
}
Run Code Online (Sandbox Code Playgroud)
此功能首次发布在我的博客上.