473,405 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Outside variables needed inside class

I have a configuration file that contains the host, username,
password, and database name required for any database connections.
The config file runs through a few if/then/else statements to
determine if the website is local or remote and if it is local if it
is the test site or "live" site then it sets the 4 variables. I am
trying to implement a webstats package that has it's own config file.
I would the new config file to be able to use the same variables as my
config file. The problem I am encountering is that the new config
file has all of its variables inside of a class and I can't seem to
get to my variables from within it. Right now the file starts like
this:

<?php
class SlimStatConfig {
/** Database connection */
var $server = "localhost";
var $username = "username";
var $password = "password";
var $database = "database";
....
?>

What I am envisioning is something to the effect of:

<?php
include('/additionalfiles/config.php');
class SlimStatConfig {
/** Database connection */
global $dbhost;
global $dbuser;
global $dbpasswd;
global $dbname;
var $server = $dbhost;
var $username = $dbuser;
var $password = $dbpasswd;
var $database = $dbname;
....
?>

I have never worked with classes before. And please spare me the "how
do you call yourself a php developer without knowing how to use
classes." Right now I just would like to get this to work with a
minimal amount of work. Thanks for your help!

May 17 '07 #1
9 2801
On May 17, 1:38 pm, Justin Voelker <justin.voel...@gmail.comwrote:
I have a configuration file that contains the host, username,
password, and database name required for any database connections.
The config file runs through a few if/then/else statements to
determine if the website is local or remote and if it is local if it
is the test site or "live" site then it sets the 4 variables. I am
trying to implement a webstats package that has it's own config file.
I would the new config file to be able to use the same variables as my
config file. The problem I am encountering is that the new config
file has all of its variables inside of a class and I can't seem to
get to my variables from within it. Right now the file starts like
this:

<?php
class SlimStatConfig {
/** Database connection */
var $server = "localhost";
var $username = "username";
var $password = "password";
var $database = "database";
...
?>

What I am envisioning is something to the effect of:

<?php
include('/additionalfiles/config.php');
class SlimStatConfig {
/** Database connection */
global $dbhost;
global $dbuser;
global $dbpasswd;
global $dbname;
var $server = $dbhost;
var $username = $dbuser;
var $password = $dbpasswd;
var $database = $dbname;
...
?>

I have never worked with classes before. And please spare me the "how
do you call yourself a php developer without knowing how to use
classes." Right now I just would like to get this to work with a
minimal amount of work. Thanks for your help!
Does the class have a constructor? If so, that's the place to pass in
the variables. It might look something like this:

public function __construct($dbhost, $dbuser, $dbpasswd, $dbname) {
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpasswd = $dbpasswd;
$this->dbname = $dbname;
}

Then, when you instantiate the class, you would do it like this:

$s = new SlimStatConfig($dbhost, $dbuser, $dbpasswd, $dbname);

May 17 '07 #2
Justin Voelker wrote:
I have a configuration file that contains the host, username,
password, and database name required for any database connections.
The config file runs through a few if/then/else statements to
determine if the website is local or remote and if it is local if it
is the test site or "live" site then it sets the 4 variables. I am
trying to implement a webstats package that has it's own config file.
I would the new config file to be able to use the same variables as my
config file. The problem I am encountering is that the new config
file has all of its variables inside of a class and I can't seem to
get to my variables from within it. Right now the file starts like
this:

<?php
class SlimStatConfig {
/** Database connection */
var $server = "localhost";
var $username = "username";
var $password = "password";
var $database = "database";
...
?>

What I am envisioning is something to the effect of:

<?php
include('/additionalfiles/config.php');
class SlimStatConfig {
/** Database connection */
global $dbhost;
global $dbuser;
global $dbpasswd;
global $dbname;
var $server = $dbhost;
var $username = $dbuser;
var $password = $dbpasswd;
var $database = $dbname;
...
?>

I have never worked with classes before. And please spare me the "how
do you call yourself a php developer without knowing how to use
classes." Right now I just would like to get this to work with a
minimal amount of work. Thanks for your help!
No problem with never using classes before - there are a lot of PHP
programmers out there who haven't.

You can't define globals that way - in fact, generally it's bad to use
globals at all.

Rather, set up the values in your constructor - that's what it's there
for, i.e. (PHP5)

class SlimStatConfig {
/** Database connection */
var $server = "localhost";
var $username = "username";
var $password = "password";
var $database = "database";

function __construct ($s, $u, $p, $d) {
$this->server = $s;
$this->username = $u;
$this->password = $p;
$this->database = $d;
}
...
}

Then create it with something like:

$sl = new SlimStatConfig($dbhost, $dbuser, $dbpasswd, $dbname);

Or, if you really MUST use globals (even though you shouldn't):

function __construct () {
global $dbhost, $dbuser, $dbpasswd, $dbname;
$this->server = $dbhost;
$this->username = $dbuser;
$this->password = $dbpasswd;
$this->database = $dbname;
}

And call it with

$sl = new SlimStatConfig();
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
May 17 '07 #3
At Thu, 17 May 2007 10:38:23 -0700, Justin Voelker let his monkeys type:
I have a configuration file that contains the host, username,
password, and database name required for any database connections.
The config file runs through a few if/then/else statements to
determine if the website is local or remote and if it is local if it
is the test site or "live" site then it sets the 4 variables. I am
trying to implement a webstats package that has it's own config file.
I would the new config file to be able to use the same variables as my
config file. The problem I am encountering is that the new config
file has all of its variables inside of a class and I can't seem to
get to my variables from within it. Right now the file starts like
this:

<?php
class SlimStatConfig {
/** Database connection */
var $server = "localhost";
var $username = "username";
var $password = "password";
var $database = "database";
...
?>

What I am envisioning is something to the effect of:

<?php
include('/additionalfiles/config.php');
class SlimStatConfig {
/** Database connection */
global $dbhost;
global $dbuser;
global $dbpasswd;
global $dbname;
var $server = $dbhost;
var $username = $dbuser;
var $password = $dbpasswd;
var $database = $dbname;
...
?>

I have never worked with classes before. And please spare me the "how
do you call yourself a php developer without knowing how to use
classes." Right now I just would like to get this to work with a
minimal amount of work. Thanks for your help!
Using global variables inside classes isn't recommended. If you can avoid
it, do so at (almost) any cost.
Either parse them to the class via a function (its constructor would be a
good place to do so):

class slimStatConfig {
var $server;
var $username;
var $password;
var $database;
var $conn;
function slimStatConfig($dbhost,$dbuser,$dbpasswd,$dbname) {
$this->server=$dbhost;
$this->username=$dbuser;
$this->password=$dbpasswd;
$this->database=$dbname;
if (!$this->$conn = @mysql_connect($this->server, $this->username,
$this->password) {
// send error message and finish gracefully
}
if (!@mysql_select_db($this->database, $this->conn)){
// send error message and finish gracefully
}
}
}
require ('/additionalfiles/config.php');
$ssc=new slimStatConfig($dbhost,$dbuser,$dbpasswd,$dbname);

....,or include the config file INSIDE the constructor and use the vars
directly:
[...]
function slimStatConfig() {
require ('/additionalfiles/config.php');
$this->server=$dbhost;
$this->username=$dbuser;
$this->password=$dbpasswd;
$this->database=$dbname;
if (!$this->$conn = @mysql_connect($this->server, $this->username,
$this->password) {
// send error message and finish gracefully
}
if (!@mysql_select_db($this->database, $this->conn)){
// send error message and finish gracefully
}
}

I am assuming you use PHP4. If not, omit the var keyword and define the
class variables public, private or protected (I think private's best here):

private $username; // etc

and your constructor:

public function slimStatConfig() //etc

or using the PHP5 __construct() function instead:

public function __construct() //etc
HTH
Sh.
May 17 '07 #4
Justin Voelker wrote:
I would the new config file to be able to use the same variables as my
config file. The problem I am encountering is that the new config
....
<?php

class BasicConfig
{
var dbHost='localhost';
var dbUser='Justin';
...
}

?>

<?php

require_once 'basic.config.php';

class ExtendedConfig extends BasicConfig
{
var dbUser='god'; // You need to change dbUser for another server
// dbHost will be available without changes
}

?>
May 17 '07 #5
Alexey Kulentsov wrote:
Ooops...

<?php

class BasicConfig
{
var $dbHost='localhost';
var $dbUser='Justin';
...
}

?>

<?php

require_once 'basic.config.php';

class ExtendedConfig extends BasicConfig
{
var $dbUser='god'; // You need to change dbUser for another server
// dbHost will be available without changes
}

?>
May 17 '07 #6
Justin Voelker wrote:
<?php
include('/additionalfiles/config.php');
class SlimStatConfig {
/** Database connection */
global $dbhost;
global $dbuser;
global $dbpasswd;
global $dbname;
var $server = $dbhost;
var $username = $dbuser;
var $password = $dbpasswd;
var $database = $dbname;
...
?>
<?php
include('/additionalfiles/config.php');
class SlimStatConfig {
/** Database connection */
var $server = $GLOBALS['dbhost'];
var $username = $GLOBALS['dbuser'];
var $password = $GLOBALS['dbpasswd'];
var $database = $GLOBALS['dbname'];
....
?>

Though I'd agree with others that globals are evil. Better to use:

<?php
include('/additionalfiles/config.php');
class SlimStatConfig {
/** Database connection */
var $db;

public function __construct ($db)
{
$this->db = $db;
}
....
?>

And simply pass the object a fully-formed database connection when you
instantiate it.

--
Toby A Inkster BSc (Hons) ARCS
http://tobyinkster.co.uk/
Geek of ~ HTML/SQL/Perl/PHP/Python/Apache/Linux
May 18 '07 #7
Can anyone explain to me why globals are so bad? I have a $phpEx
variable in my main config file and i use "global $phpEx" inside of
certain functions that return links so I don't have to change a
hundred links if I change my php extension to something else (php4,
php5). Thanks for the great help everyone! Now if I can just figure
out how to implement your solutions...

May 18 '07 #8
Justin Voelker wrote:
Can anyone explain to me why globals are so bad? I have a $phpEx
variable in my main config file and i use "global $phpEx" inside of
certain functions that return links so I don't have to change a
hundred links if I change my php extension to something else (php4,
php5). Thanks for the great help everyone! Now if I can just figure
out how to implement your solutions...
In this example, a constant would be a far better idea:

define('SCRIPT_FILENAME_SUFFIX', '.php');
/* ... */
echo '<a href="login' . SCRIPT_SUFFIX . '">Login</a>';

One argument against the use of a global variable here might be something
like:

// Figure out extension for PHP source code files
function phpSourceExt ()
{
global $phpExt;

if (preg_match('/^\.php([0-9]+)$/i', $phpExt, $matches))
{
return ".php-v{$matches[1]}-source";
}
elseif ($phpExt = '.PHP')
{
return '.PHPS';
}
else
{
return '.phps';
}
}

See what I did there? Single equals sign instead of a double equals sign
in the elseif clause. You can accidentally modify the global variable, and
then the rest of the script will use the modified value. If you use a
constant, PHP raises an error if you try to modify it.

So one bit of code might modify a global variable, and another piece of
code, somewhere way off in another file tries to read the global variable
and has trouble. This is called "action at a distance" and is generally
considered bad. Debugging this kind of thing can be very frustrating, as
you don't know where something went wrong -- so many bits of code using
the same variable.

Which is not to say that global variables aren't occasionally useful. Evil
things can be useful at times. Even Satan himself can be quite handy. But
the forces of evil need great consideration and respect before use. They
have almighty power and need to be handled with care.

Before using global variables, have a good think about if there's a better
way of doing things.

--
Toby A Inkster BSc (Hons) ARCS
http://tobyinkster.co.uk/
Geek of ~ HTML/SQL/Perl/PHP/Python/Apache/Linux
May 18 '07 #9
Justin Voelker wrote:
Can anyone explain to me why globals are so bad? I have a $phpEx
variable in my main config file and i use "global $phpEx" inside of
certain functions that return links so I don't have to change a
hundred links if I change my php extension to something else (php4,
php5). Thanks for the great help everyone! Now if I can just figure
out how to implement your solutions...
The biggest problem is you might change the global somewhere due to a
bug in the program - and have to spend hours trying to figure out where
you went wrong.

A secondary problem is that when you modify your code you can
unintentionally insert bugs into the code by changing the value.

Another potential problem occurs when you include another package in
your scripts which just happens to use the same global - what does it
do? This can even be one of your own scripts, added because you
rearranged the code.

Passing the values as parameters allows you to control what's going on.
And if you have to change the value in your function, pass by reference.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
May 18 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: bst | last post by:
Is there a way to iterate through member variables of different names, of course, one by one from the very first one in a while loop, for example? Thanks!
2
by: David A. Beck | last post by:
I have a shared class as a part of a ASP.NET project. I'm adding routines that are used on all the WebForm aspx.vb pages. I can't figure out how to read the session variables in this class. sX =...
1
by: Frank Rizzo | last post by:
I have a class that's being instantiated and called from the code-behind class. How can I get access to the Application variables from this class? Thanks
1
by: Nathan | last post by:
Hi, I have created a class library creating a number of forms and a few public variables. I have a project that references the .dll for this class library, and in that project I need to access...
5
by: Jesper Schmidt | last post by:
When does CLR performs initialization of static variables in a class library? (1) when the class library is loaded (2) when a static variable is first referenced (3) when... It seems that...
3
by: sam_cit | last post by:
Hi Everyone, When a variable is declared as const, it is initialized along with the declaration, as modification later on is not possible. Having seen that, how about const variables in a class?...
2
by: Edwina Rothschild | last post by:
Can anyone explain to me why globals are so bad? I have a $phpEx variable in my main config file and i use "global $phpEx" inside of certain functions that return links so I don't have to change a...
7
by: beginner | last post by:
Hi Everyone, I have encountered a small problems. How to call module functions inside class instance functions? For example, calling func1 in func2 resulted in a compiling error. "my module...
3
by: vern | last post by:
Greetings, how would I pass variables that are outside a class ... to a class? Such as ... $variable_one = 1; $variable_two = 2; class this_is_a_class { public $variable_one; public...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.