从公共范围获取变量以连接数据库 [英] getting a variable from a public scope to connect database
问题描述
<?php
$settings['hostname'] = '127.0.0.1';
$settings['username'] = 'root';
$settings['password'] = 'root';
$settings['database'] = 'band';
$settings['dbdriver'] = 'mysql';
/**
* DATABASE
*/
class database
{
protected $settings;
function __construct()
{
}
function connect()
{
$this->start = new PDO(
$this->settings['dbdriver'] . ':host='.
$this->settings['hostname'] . ';dbname='.
$this->settings['database'],
$this->settings['username'],
$this->settings['password'],
array(PDO::ATTR_PERSISTENT => true));
$this->start->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
}
}
?>
好的,我仍然是学生,所以今天我正在学习范围和连接数据库 问题是我如何将$ settings从类中放入受保护的$ settings中?
ok im still a student so today im learning about scope and connections database the question is how can i put the $settings out of the class in to the protected $settings in class ?
推荐答案
在显示的代码中您已经走在正确的道路上:根本不要使用公共(全局)范围-在OOP中,不认为这样做是一种好习惯依赖全局变量,因为它破坏了封装.而是在初始化对象时将设置注入到对象中.
You are already on the right path in the code you show: Don't use public (global) scope at all - it's not regarded good practice in OOP to rely on global variables, because it breaks encapsulation. Instead, inject the settings into the object when initializing it.
您可以添加一个构造函数来做到这一点:
You could add a constructor to do that:
function __construct($settings)
{
$this->settings = $settings;
}
,然后像这样初始化类:
and then initialize the class like so:
$database= new database($settings);
或类似地,以防止带有敏感数据的变量浮动:
or like so, to prevent a variable with sensitive data floating around:
$database= new database(array('hostname' => '127.0.0.1',
'username' => 'root',
'password' => 'root',
'database' => 'band',
'dbdriver' => 'mysql'));
作为旁注,在生产中使用时,为了安全起见,请考虑在连接后从阵列中删除password
变量.没什么要紧,只是要做的一件好事.
As a side note, in production use, consider deleting the password
variable from the array after connecting, for security. It's nothing essential but a nice additional thing to do.
这篇关于从公共范围获取变量以连接数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!