Как я могу получить доступ к содержимому этого массива PHP? - PullRequest
0 голосов
/ 24 января 2010

Ниже приведены файлы в 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);
    ?>

Ответы [ 3 ]

2 голосов
/ 24 января 2010

Код у вас работает нормально для меня.
Проверьте вашу версию PHP, этот __get поддерживается после v5.2.0

echo $config->ip; // displays fine 127.0.0.1
1 голос
/ 24 января 2010

-> используется для учеников. У вас нет класса, у вас есть массив, поэтому вместо него используйте скобки ($ config [xxxx] вместо $ config-> xxxx).

1 голос
/ 24 января 2010

Возвращает массив, поэтому используйте ...

 echo $config['ip'];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...