Jump to content

How to access $config['var'] variable in Class.


keldorn

Recommended Posts

I'm more in procedural, anyways I am trying out OOP.

I have this class that does Mysql Database stuff. But I hit a wall with this.

I have variables like $config['database_pass'] = "password" in a config.php file.

 

I can't access it inside this class. So  how is done properly?

 

I keep getting errors. Like "unexpected T_VARIABLE"

 

 

 

class database{

public function __construct(){

/* Connect to mysql (Area of my problem)*/
$sql = array();
    $link = mysql_connect($CONFIG['database_host'], $CONFIG['database_user'], $CONFIG['database_pass']) or die('Could not connect: ' . mysql_error());
    $db_selected = mysql_select_db($CONFIG['database_database'],$link) or die(mysql_error());


}



// Return array of categories
public function get_cat(){

    $sql = mysql_query("SELECT * FROM category") or die(mysql_error() . " In category.php file in class database function get_cat");

    while($line = mysql_fetch_assoc($sql)) {


      $tmp[] = $line;
	  
    }

	if(is_array($tmp)){

	  return $tmp;

	} else {

	  return false;

	}
    }


}

Yes that works, ;)

I was reading however that method is the "undesirable" way to do it. (I could also include the config.php file in the __construct() to achieve that same thing I believe which would be even more undesirable).

 

Except they forgot to mention the "proper" way or why its the least preferred method. haha I'm only left with unanswered questions.

 

If anyone could fill in why using global inside a class is undesirable and what is the better method that would great. I guess for now I'll use global inside the __construct.

 

keldorn

I think the reason that the global is the undesired method is because it might used up other variable name.

 

In Zend framework, I will be using the constant method: Zend_Registry::set() & Zend_Registry::get() which will get and set whatever variable I want.

 

With that, you will have your own namespace without messing with other variable name.

 

Eg:

 

Zend_Registry::set('config', $config);  //probably put this on your initialization...

 

in your class method:

function __construct() {

    $config = Zend_Registry::get('config');

}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.