php - 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 );     } } ?> 

ok im still student today im learning scope , connections database question how can put $settings out of class in protected $settings in class ?

you on right path in code show: don't use public (global) scope @ - it's not regarded practice in oop rely on global variables, because breaks encapsulation. instead, inject settings object when initializing it.

you add constructor that:

function __construct($settings)  {    $this->settings = $settings;  } 

and initialize class so:

 $database= new database($settings);  

or so, prevent variable sensitive data floating around:

 $database= new database(array('hostname' => '127.0.0.1',                   'username' => 'root',                   'password' => 'root',                   'database' => 'band',                   'dbdriver' => 'mysql')); 

as side note, in production use, consider deleting password variable array after connecting, security. it's nothing essential nice additional thing do.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -