Jump to content

[SOLVED] Global Variables within Classes


kael.shipman

Recommended Posts

Hey,

 

I have a class whose functions all use the same global variables (a specific mysql connection), but when I tried to make the global $sql_connection local to the class, it threw errors:

 

<?php
class cha {
global $sql_connection; //Error here: "Parse error: syntax error, unexpected T_GLOBAL, expecting T_FUNCTION"

function fah() {
  @mysql_query("insert something",$sql_connection);
}

function lah() {
  @mysql_query("select something",$sql_connection);
}

//a few more functions
}
?>

 

I assume this means that I can't use "global" in the context of a class, but is there something comparable or do I have to localize the $sql_connection variable within each individual function?

 

Thanks,

Kael

Link to comment
https://forums.phpfreaks.com/topic/58078-solved-global-variables-within-classes/
Share on other sites

there is no global contect in classes.

 

you need to pass the $sql_connection to the class by assigining it in the script creating the class like so...

 

<?php

$clss_ref = new cha;

$clss_ref->dbconn = $sql_connection;

?>

 

then in the class itself you can then use $this->db_conn;

 

OR if you only have the one just leave it out of the mysql_query functio - php automatically uses the last connection it created if no resource is passed in the argument...

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.