PHP 是否允许在 Java 中使用 *.properties 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5900077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:20:33  来源:igfitidea点击:

Does PHP allow *.properties file as in Java?

javaphp

提问by Alex

Is there a way to use a *.properties file in PHP as you do in Java? I'd like to store some application-level constants in a properties or XML file and easily call them from throughout my code. Your guidance is much appreciated. Thanks.

有没有办法像在 Java 中一样在 PHP 中使用 *.properties 文件?我想在属性或 XML 文件中存储一些应用程序级常量,并在我的代码中轻松调用它们。非常感谢您的指导。谢谢。

回答by ceejayoz

PHP can natively load and parse .inifiles using parse_ini_file().

PHP 可以.ini使用parse_ini_file().

You can also set up constants in an include file using define().

您还可以在包含文件中使用define().

If you're set on XML, look into PHP's XML functionality. The simplest solution is probably to use SimpleXML.

如果您使用 XML,请查看 PHP 的 XML 功能。最简单的解决方案可能是使用SimpleXML

回答by dusan

You can also use a PHP file containing an array to store data. Example:

您还可以使用包含数组的 PHP 文件来存储数据。例子:

config.php

配置文件

<?php 
return array(
    'dbhost' => 'localhost',
    'title'   => 'My app'
);

Then in another file:

然后在另一个文件中:

$config = require 'config.php':
echo $config['title'];

回答by Rafael Sanches

parse_ini_filedoesn't have anything to do with *.propertiesfiles in Java environments.

parse_ini_file*.propertiesJava 环境中的文件没有任何关系。

I create this function, that does the exact same thing as its equivalent in Java:

我创建了这个函数,它的作用与 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;
}

This function was first posted on my blog.

这个功能最早发布在我的博客上

回答by Sander Versluys

Well, you could perfectly put some configuration in a properties file and do the parsing yourself. But in PHP it's not the appropriate format todo so.

好吧,您可以完美地将一些配置放在属性文件中并自己进行解析。但在 PHP 中,这样做不是合适的格式。

I would define some constants and put them in a seperate php config file (like config.php) and include this where needed.

我会定义一些常量并将它们放在一个单独的 php 配置文件(如 config.php)中,并在需要的地方包含它。

Other options would be to actually put the configuration in a xml file and use a xml librarythe read it. YAML(php.net) is also a popular option for simple readable configuration.

其他选项是将配置实际放在 xml 文件中并使用xml 库读取它。YAML( php.net) 也是简单可读配置的流行选项。

回答by PatrickB

As far as I know, there is no PHP built-in functions to read and handle .properties files. If the application you wrote in PHP needs to read Java .properties files, you need to code your own solution by reading the file and create your own .properties parser.

据我所知,没有 PHP 内置函数来读取和处理 .properties 文件。如果您用 PHP 编写的应用程序需要读取 Java .properties 文件,您需要通过读取文件编写自己的解决方案并创建您自己的 .properties 解析器。

Otherwise, as mentionned by other members here, you can store configuration information into a .ini file. PHP provides native functions to load and parse .ini files.

否则,正如其他成员所提到的,您可以将配置信息存储到 .ini 文件中。PHP 提供了本地函数来加载和解析 .ini 文件。

If you prefer the information is stored into a XML file with the PHP XML parser (PHP Manual Function Reference XML Manipulation).

如果您愿意,可以使用 PHP XML 解析器(PHP 手册函数参考 XML 操作)将信息存储到 XML 文件中。

Personally, I prefer to store configuration / application constant values into an array. I created a Configuration class that handle configuration file.

就个人而言,我更喜欢将配置/应用程序常量值存储到数组中。我创建了一个处理配置文件的配置类。

There is an example here :

这里有一个例子:

Configuration file example (ex : config.php)

配置文件示例(例如:config.php)

<?php
    // Typical configuration file
    $config['database']['type']         = 'mysql';
    $config['database']['host']         = 'localhost';
    $config['database']['username']     = 'root';
    $config['database']['password']     = 'your_password';
    $config['database']['database']     = 'your_project';
    $config['date']['timezone']         = 'America/Montreal';
?>    

Class Configuration

班级配置

<?php
    class Configuration
    {
        protected $configuration;

        function __construct($filename)
        {
            // CFG_PATH : i.e --> define('CFG_PATH',dirname(__FILE__) . '/cfg/');
            require(CFG_PATH . $filename);
            $this->setConfiguration($config);
        }

        public function getConfiguration($configuration)
        {
            return $this->configuration[$configuration];
        }

        public function setConfiguration($configuration)
        {
            $this->configuration = $configuration;
        }
    }
?>

Typical use example

典型使用示例

<?php

    // Your class definitions, variables, functions...

    function __construct() {

        $this->configuration = new Configuration(CFG_FILE);
        $this->set_Timezone($this->configuration->getConfiguration('date'));

    }

    private function set_Timezone($configuration)
    {
        date_default_timezone_set($configuration['timezone']);
    }

?>

Other example (Controller and DAO)

其他示例(控制器和 DAO)

Controller

控制器

<?php

    protected function doPost() {
        ...
        $configuration = new Configuration(CFG_FILE);
        $dao = new DAO($configuration->getConfiguration('database'));
        ...
    }

?>  

DAO example

DAO 示例

<?php

    function __construct($configuration) {
        // Build DSN (Data Source Name) string 
        if ($configuration['type'] == 'mysql') {
            $this->dsn = '(type):host=(host);dbname=(database);charset=UTF8';
            $this->dsn = str_replace('(type)', $configuration['type'], $this->dsn);
            $this->dsn = str_replace('(host)', $configuration['host'], $this->dsn);
            $this->dsn = str_replace('(database)', $configuration['database'], $this->dsn);
            $this->options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'');
            try
            {
                $this->databaseHandle = new PDO($this->dsn, $configuration['username'], $configuration['password'], $this->options);
            }
            catch (PDOException $e)
            {
                ...
            }
        }
        else
        {
            ... 
        }
    }

?>

If you use Spring framework in Java and you want a similar solution for messages.properties in PHP, you can adapt the same solution mentionned above. Of course, the behavior won't be the same as Java, but, with Locale class, you can create functions that handle messages/labels in your PHP application based on location where client is located.

如果您在 Java 中使用 Spring 框架并且想要在 PHP 中为 messages.properties 提供类似的解决方案,则可以采用上述相同的解决方案。当然,行为不会与 Java 相同,但是,使用 Locale 类,您可以根据客户端所在的位置在 PHP 应用程序中创建处理消息/标签的函数。

With this kind of solution based on arrays, I think this will help you to define required values in your application and organize your configuration data as well. Of course, there is many other ways to achieve this, but I think is solution works.

使用这种基于数组的解决方案,我认为这将帮助您在应用程序中定义所需的值并组织您的配置数据。当然,还有很多其他方法可以实现这一点,但我认为解决方案是有效的。

回答by MARKODY

function getLocale($file){
    $locales = array();
    $accessible = fopen($file, "r");
    if (!$accessible) return null;
    while (($line = fgets($accessible)) !== false) {
        $pos = strpos($line, '=');
        if (!$pos) continue;
        $name = substr($line, 0, $pos);
        $value = substr($line, $pos + 1, strlen($line));
        $locales[$name] = $value;
    }
    return $locales;
}
getLocale('lang/eng.properties');

回答by sumit

In PHP .ini files serve almost same functionality. There are simple methods to read constants from these files.

在 PHP 中,.ini 文件提供几乎相同的功能。有一些简单的方法可以从这些文件中读取常量。

Further most of the PHP frameworks implement it with configuration files mostly with extension .php.

此外,大多数 PHP 框架使用配置文件来实现它,大部分配置文件扩展名为 .php。

for example in cake php we have Configure class which provides like Configure::read('VarName') and Configure::write('VarName',VarValue);

例如在 cake php 中我们有 Configure 类,它提供了像 Configure::read('VarName') 和 Configure::write('VarName',VarValue);

once written this can be accessed in the scope of file inclusion.

一旦写入,就可以在文件包含的范围内访问。