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
Share on other sites

You could probably try something like, not sure, and haven't tested it.

 

<?php
class blah {
    var $sqlc;

    function __construct()
    {
         global $sql_connection;
         $this->sqlc = &$sql_connection;
    }

}
?>

Link to comment
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...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.