在PHP类中使用来自其他文件的变量

时间:2016-01-13 03:46:23

标签: php

我有一个名为config.php的文件中的数据库凭据变量:

$db_server = 'localhost';
$db_user = 'username';
$db_password = 'secret'
$db_name = 'dbname';

现在,我在/ class文件夹下有一个PHP类,它对CRUD进程完全正常。名为MysqlCrud.class.php

class Database {

    private $db_host = 'localhost';  // Change as required
    private $db_user = 'username';  // Change as required
    private $db_pass = 'secret';  // Change as required
    private $db_name = 'dbname';    // Change as required

}

但是,我想使用config.php中的集中变量。这就是为什么我添加这样的行:

include('../config.php');
class Database {

    global $db_server;
    global $db_user;
    global $db_password;
    global $db_name;

    private $db_host = $db_server;  // Change as required
    private $db_user = $db_user;  // Change as required
    private $db_pass = $db_password;  // Change as required
    private $db_name = $db_name;    // Change as required

}

但是,我收到以下错误消息:

Parse error: syntax error, unexpected 'global' (T_GLOBAL), expecting function (T_FUNCTION) in /home/*** on line **

为什么我不能在Database类中使用config.php文件中的变量?我在这做错了什么?谢谢。

4 个答案:

答案 0 :(得分:3)

在课堂内,您只能拥有会员声明。全局变量不是类成员,因此您不能在类中使用它们。但你可以在方法中使用它们。

class Database {
    private $db_host;
    //... the rest of them here

    //class constructor. Gets called every time you create an instance of this class.
    function __construct() {
        global $db_server;
        global $db_user;
        global $db_password;
        global $db_name;

        $this->db_host = $db_server;
        //.... you get the idea
    }
}

编辑2017-07-11:

不要这样做。不要使用全局变量。它们很容易在某处覆盖,你最终会调试很多。另外,要求global关键字是脏的。 @ br3nt提供了适当的部分解决方案。但它仍然使用全局变量并在全局范围内初始化$db变量。

如果您可以访问Apache中的站点配置,例如,对于该网站,您可以使用mod_env在环境变量中设置配置。例如:

<VirtualHost *:80>
    .....
    SetEnv DB_USER=myDatabaseUser
    SetEnv DB_PASSWORD=12345
    ...
</VietualHost>

然后,您可以使用getEnv('DB_USER') http://php.net/manual/en/function.getenv.php

在PHP中阅读此内容

另一个选择是让你的配置返回一个数组:
的config.php

<?php
return [
    'db_user'=>'myDbUser,
    'db_password'=>'12345'
];

你应该有一个单一的入口点,确保对该配置的只读访问。

<强> Config.class.php

<?php
class Config {
    private $_config;
    public function __construct() {
        $this->_config = include('path/to/config.php');
    }

    public function __get($key) {
        if(isset($this->_config[$key])) {
            return $this->_config[$key];
        }
        return null;
    }
}

用法:

$config = new Config();
$dbUser = $config->db_user;
$dbPassword = $config->db_password;

编辑2,当天

为什么全局变量不好?

拥有全局变量很好,因为你可以随处访问它们,对吧?将所有班级成员公之于众也是一种好习惯吗?不,假设您在许多地方使用了全局变量。有人不小心写了这个:

if($myGlobalVariable='something') { ... }

他的代码只是一个无人问津的奇怪错误。但是你的代码中断了,因为你实际上依赖于$myGlobalVariable的确切值。你看一下配置,看看它是正确的值,然后抓住你的头。

这只是一个案例。对共享资源的无阻碍读写访问可能是危险的。它很容易覆盖,不会输出错误。它还污染了全球空间。

如果您在配置文件中有全局功能,那么这也是一种代码味道。将配置文件视为静态文本文件,甚至不应包含代码。他们是PHP文件的唯一原因是速度快,容易,并且更难以破坏安全性。

答案 1 :(得分:3)

也许你可以这样试试:

function connDB()
{
    $conn=mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("database") or die(mysql_error()); 
    return $conn;
};

将此函数放在配置文件或其他文件中,例如globalFunctions.php(包含您需要的所有常规功能)。只需在每次需要时调用此功能。

答案 2 :(得分:3)

您选择使用的方法的问题是该类不再可重用。每次实例化Database类时,它都将使用全局变量。

我更倾向于这样设置:

<强> database.php中

class Database {

  private $host;
  private $db_name;
  private $username;
  private $password;

  function __construct($host, $db_name, $username, $password) {
    $this->host = $host;
    $this->db_name = $db_name;
    $this->username = $username;
    $this->password = $password;
  }
}

然后在文件中使用Database类:

include('../config.php');

$db = new Database($db_server, $db_name, $db_user, $db_password);

答案 3 :(得分:1)

以下是使用1- Change the ISOLATION level to READ COMMITTED. In this isolation level, it is normal and expected that query results can change during a transaction, so there is no need to create locks to prevent that from happening. 2- innodb_locks_unsafe_for_binlog = 1. Disables the gap locks except for foreign-key constraint checking or duplicate-key checking.

将类成员设置为全局值的选项
__construct()

由于我们使用的是Assignment by Reference,因此内部类成员与全局成员的变量相同(因此根据需要进行更改)。

此外,如果您想避免编写include('../config.php'); class Foo { private $db_host; private $db_user; private $db_pass; private $db_name; public function __construct() { global $db_server; global $db_user; global $db_password; global $db_name; $this->db_host = &$db_server; // Change as required $this->db_user = &$db_user; // Change as required $this->db_pass = &$db_password; // Change as required $this->db_name = &$db_name; // Change as required } } ,可以使用保留变量global,如documentation中所述:

  

一个关联数组,包含对当前在脚本全局范围内定义的所有变量的引用。变量名是数组的键。

所以你的代码可能会变成这样:

$GLOBALS