簡體   English   中英

如何訪問此PHP數組的內容?

[英]How can I access the contents of this PHP array?

以下是PHP中要嘗試包含的文件,該文件將數組保存到類中,然后訪問該數組。 如果我在上面運行print_r(),我會得到結果,但是如果我嘗試單獨訪問數組項,我什么也沒有,有人可以幫我嗎?

<?php
// config.class.php
/*
example usages
$config = Config::getInstance(PATH_TO_CONFIG_FILE, FILE_TYPE);
echo $config->url;
echo $config->test;
echo $config->ip;
*/

class Config
{
    private static $instance = null;
    private $options = array();

    /**
     * Retrieves php array file, json file, or ini file and builds array
     * @param $filepath Full path to where the file is located
     * @param $type is the type of file.  can be "ARRAY" "JSON" "INI"
     */ 
    private function __construct($filepath, $type = 'ARRAY')
    {
        switch($type) {
            case 'ARRAY':
                $this->options = include $filepath;
                break;

            case 'INI':
                $this->options = parse_ini_file($filepath, true);
                break;

            case 'JSON':
                $this->options = json_decode(file_get_contents($filepath), true);
                break;    
        }
    }

    private function __clone(){}

    public function getInstance($filepath, $type = 'ARRAY')
    {
        if (null === self::$instance) {
            self::$instance = new self($filepath, $type = 'ARRAY');
        }
        return self::$instance;
    }

    /**
     * Retrieve value with constants being a higher priority
     * @param $key Array Key to get
     */
    public function __get($key)
    {
        if (isset($this->options[$key])) {
            return $this->options[$key];
        }
    }

    /**
     * Set a new or update a key / value pair
     * @param $key Key to set
     * @param $value Value to set
     */
    public function __set($key, $value)
    {
        $this->options[$key] = $value;
    }

}
?>

這是config_array.ini.php文件...

<?php
/**
 * @Filename config_array.ini.php
 * @description Array to return to our config class
 */
return array(
    'ip' => $_SERVER['REMOTE_ADDR'],
    'url' => 'http://www.foo.com',
    'db'  => array(
        'host' => 'foo.com',
        'port' =>  3306
    ),
    'caching' => array(
        'enabled' => false
    )
);
?>

這是我正在嘗試做的...

   <?PHP
    $config = Config::getInstance('config_array.inc.php', 'ARRAY');

    // this does not show anything
    echo $config->ip;

    // this works
    print_r($config);
    ?>

您擁有的代碼對我來說很好用。
檢查您的PHP版本,此__get在v5.2.0之后受支持

echo $config->ip; // displays fine 127.0.0.1

它返回一個數組,所以使用...

 echo $config['ip'];

->用於班級成員。 您沒有類,但有一個數組,因此請使用方括號($ config [xxxx]代替$ config-> xxxx)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM