473,748 Members | 2,398 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2826
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($db host, $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*******@attgl obal.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,$dbn ame) {
$this->server=$dbhost ;
$this->username=$dbus er;
$this->password=$dbpa sswd;
$this->database=$dbna me;
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,$dbn ame);

....,or include the config file INSIDE the constructor and use the vars
directly:
[...]
function slimStatConfig( ) {
require ('/additionalfiles/config.php');
$this->server=$dbhost ;
$this->username=$dbus er;
$this->password=$dbpa sswd;
$this->database=$dbna me;
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='localho st';
var dbUser='Justin' ;
...
}

?>

<?php

require_once 'basic.config.p hp';

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='localh ost';
var $dbUser='Justin ';
...
}

?>

<?php

require_once 'basic.config.p hp';

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*******@attgl obal.net
=============== ===
May 18 '07 #10

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

Similar topics

10
8770
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
1455
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 = CSTR(Session("XMAN")) tells me I cannot refere to an instance name of a class from within a shared method ...
1
1200
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
1218
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 those public variables. For instance, the main app calls a form in the referenced library, that form changes the value of PublicVar1 and then closes. The main app now needs to know the value of PublicVar1.
5
6779
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 (1) holds for unmanaged C++ code, but not for managed code. I have class library with both managed and unmanaged static variables that are not referenced by any part of the program. All the
3
19266
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? Is it possible for a class to have const variables? As just declaring the class alone doesn't create any memory, only creation of objects results in memory allocation for the object. Thanks in advance!!!
2
644
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 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 regards, Giovanni Macra
7
8525
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 here" def func1(): print "hello"
3
6301
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 $variable_two;
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8830
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9544
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9247
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8243
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4606
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3313
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2783
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.