Jump to content

Recommended Posts

I've googled, I've php.netted, I've phpfreakked, and can't find a simple explanation (not really).

 

Let's say I have something like this:

 

$foo = "bar";

function dothis() {
echo $foo;
$something = "foobar";
echo $something;
global $something;
}

function dothat() {
global $foo;
echo $foo;
echo $something;
}

 

There are three questions here that I want to know. If I define a variable outside all functions, could that function access that variable correctly [function dothis()] Or do I need to make that variable a global before I can use it [function dothat()]. If I define a variable in one function [function dothis(), variable $something], do I need to make it global in that same function in order for the other function to call it (if it's possible?) Could I have also made it global in [function dothat()]?

 

Hopefully, you understand what I'm saying here.


Second question: constants. I understand the basic idea, define a "KEYWORD" and register a non-changing value for it.

 

Would this work?

 

$username = validate($_POST["username");//assume validate is to "check" it the user data
define('USERNAME',$username);

 

That should work right?


Finally, my last question, a bit of a blunder. Let's say I have some sort of a user login management website of sorts. General idea would be different pages, profiles, login, logout, register, etc...

 

So a user logs in, I call a class to validate this user. I use another class (class User) to fetch all the data for that particular user, set it into a mega array such as $user["id"] or $user["email"] to store all data to be called later.

 

Page1.php

include "someuserclass.php"
$user = new User;
$user->setuser($username);
$user->compile_array();//sets $user to contain the array that is returned by the class function
//from this point, I can easily call data, etc...

 

Now, wait. Let's say I go to Page2.php, does this mean I have to re-initiate the class, do the same thing as I did for Page1.php (with the include, initiate class, setuser, and then compile data)? Is there some way to maintain the class over different pages (as you would do with cookies or sessions, without actually using cookies or sessions)? The only way that I can think of doing this is to include this in the "head.php" page which contains the header stuff, like top of the layout, title, etc... like so:

 

Head.php

include "someuserclass.php"
include "somerequiredfunctions.php";
include "database_conn.php";
$user = new User;
$user->setuser($username);
$user->compile_array();//sets $user to contain the array that is returned by the class function
//insert some html here

 

Page1.php

include "Head.php";
//do other stuff here, etc..

 

Page2.php

include "Head.php";
//do some other stuff here...

 

My biggest worry is that since I'm fetching data from the database, that this makes a NEW call to the database for each page that I load (to get user data). Is there anyway to maximize efficiency, and cut-down on server usage/memory? [hopefully, something that may include a mysql_free_result() function, which I don't know WHEN to use it, or why you would use it if it clears your variables...]


Thanks :-o (these are ideas that are probably common with most people). I think my biggest problem would just basically be that I'm a bit set in my ways, and I'm trying to pull in other things to help make my coding leaner, and cleaner.

Link to comment
https://forums.phpfreaks.com/topic/74815-constants-and-globals-what-are-they/
Share on other sites

1.  You must declare it as global inside EVERY function that accesses it, BEFORE you access it.  You can think of the "global" instruction as meaning "Import this variable into local scope."

 

$foo = 'bar';
function dothis() {
  global $foo;
  # Now you can treat access $foo as a normal variable
}

 

2.  Yes, you can dynamically define constants.  Silly huh?  But you can't redefine them.  Example:

 

$var = 'bar';
define('FOO', $var);
print FOO . "\n";
define('FOO', 'baz');
print FOO . "\n";

 

3.  Sessions!  You must be careful to ensure your classes are defined before session data is read though.  People in the OOP sub-forum can help you with that I'm sure, I'm a bit of an OO noob.

1. So once I define it as a global inside a function, that function and only that function can use it? What about over different pages? (I'm assuming it works the same way as a normal variable) What about specific security issues with this thing?

 

2. Nice explanation, I get constants now :-D

 

3. Can you explain a bit how to use sessions for this or just quote my thing, send it over to OOP and see what they give me?

For 1, no the function doesn't take ownership of the variable.  The variable is shared between the function scope and global scope.  When the function finishes, the variable goes back to being a standard global variable.

 

If another function then declares the same variable as global, then the variable is shared by that function until it finishes.  You can even call another function inside that function which also shares the same variable.  There's actually a hard limit of around 64,000 times you can do this at one time, but it's unlikely you'll hit that :)

 

For sessions, try this to get you going.

 

session_start();
print "\$_SESSION[foo] = {$_SESSION['foo']}<br>";
if (empty($_SESSION['foo'])) {
  print "Setting it to 'bar'<br>";
  $_SESSION['foo'] = 'bar';
}

 

The first time you run it, it will show that $_SESSION['foo'] is empty.  But on all subsequent runs, it will show it to contain "bar".  Regarding objects in sessions, yes you should try the OOP forum :)  But first you should learn the general idea behind sessions.  Basically they let you keep variables between script runs.  Session data is stored in a file on the server, and is identified by a cookie.

to store an object in a session variable you need to serialize() it.

 

http://us3.php.net/serialize

 

page 1

session_start();
include 'foo.class.php'

$bar = new foo();

$_SESSION['bar'] = serialize($bar);

 

page 2

session_start();
include 'foo.class.php'

$bar = unserialize($_SESSION['bar']);

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.