PHP只获取数组的第一个元素

时间:2015-01-08 08:27:21

标签: php arrays

您好我正在登录并注册脚本。我为我的Config提供了全局数组。但是当我试图连接到我的数据库时。他无法从阵列中仅通过主机获取它。他不会深入内心。我得到的每件东西都只有127.0.0.1,所以我想拥有用户名,我会得到127.0.0.1。我不知道什么是错的,但我觉得我的Config.php有些不对劲。这也是我在屏幕上的输出。有人知道我做错了什么吗?

我只收回主机阵列。当我想要用户名或数据库名称时,我会得到主机。 enter image description here 这是我的代码。

的index.php

<?php
require_once 'core/init.php';


DB::getInstance();

的init.php

    <?php
session_start();

$GLOBALS['config'] = array(
    'mysql' => array(
                    'host'      => '127.0.0.1',
                    'username'  => 'root',
                    'password'  => '',
                    'db'        => 'login'

                    ),
    'remember' => array(
                    'cookie_name'   => 'hash',
                    'cookie_expiry' => '648000'
    ),

    'session' => array(
        'session_name' => 'user'
    )
);

spl_autoload_register(function($class){
    require_once 'classes/' . $class . '.php';
});

require_once '/functions/sanitize.php';

的config.php

<?php
class Config{
    public static function get($path = null){
        if($path){
        $config = $GLOBALS['config'];
        foreach($config as $key =>$value){
            if(isset($value)){
                $config1 = $value;
                foreach ($config1 as $key =>$list){
                    return  $list;
                }
            }

        }
          return false;
        }    

    }
}

db.php中

<?php

class DB{
    private static $_instance = null;
    private $_pdo, $_query, $_error = false, $_result, $_count = 0; 

    private function __construct(){
        try{
            $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
        }catch(PDOException $e){
            echo Config::get('mysql/host') . Config::get('mysql/db') . Config::get('mysql/db'); // Only for testing getting 127.0.0.1 back for each of them.

        }
    }


    public static function getInstance(){
        if(!isset(self::$_instance)){
            self::$_instance = new DB();
        }
        return self::$_instance;
    }
}

2 个答案:

答案 0 :(得分:5)

private static $_istance = null;

Tyyyypoooooooooooo :) n失踪

修改

Typoooooooooo 2号

'msql' => array(

应该{​​{1}},这就是你的配置无法加载的原因。

答案 1 :(得分:0)

在重写我的Config.php类之后,它起作用了。

<?php
class Config{
    public static function get($path = null){
        if($path){
            $config = $GLOBALS['config'];
            $path = explode('/', $path);

            foreach($path as $bit){
                if(isset($config[$bit])){
                    $config = $config[$bit];
                }
            }   
            return $config;
        }
    }
}