homepage Welcome to WebmasterWorld Guest from 54.226.173.169
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Accessing Classes Without Using Global Vars
How can I access a class in php without declaring a global variable
bpejman




msg:4019811
 6:13 pm on Nov 5, 2009 (gmt 0)

Hi,

I've been reading a lot about how the use of global variables is not recommended due to security issues. Personally, I don't like the use of global variables, however, since the website I'm building is strictly class-based, I would need to access its methods somehow.

What is the best approach for this so I can avoid global variables?

I have 2 php files, index.php and session.php. In index.php, I'm simply including session.php like so:

/* index.php */
<?
include_once("session.php");
?>
<html>
<body>
</body>
</html>

In session.php, I have created a class like so:

/* session.php */
<?
class Session
{
public function Session(){}
public function method1(){}
public function method2(){}
};

$session = new Session; // Notice the use of global var here

?>

Do you think the following would be better?

/* session.php */
<?
class Session
{
public function Session(){}
public function method1(){}
public function method2(){}
};

StartSession();

function StartSession() { $session = new Session; }

?>

The problem with this approach is that $session variable will not be accessible by my php pages since its scope is limited to the StartSession function so I don't know how to call the methods within the Session class.

Unless, are there any problems with me doing the following at the top of index.php instead like so or is that the same as global variable use?

/* index.php */
<?
include_once("session.php");
$session = new Session;
?>
<html>
<body>
</body>
</html>

Thanks for any suggestions and help. I'm not sure how others are tackling this problem without the use of global variables.

Bobby

 

JohnCanyon




msg:4020692
 9:12 pm on Nov 6, 2009 (gmt 0)

Bobby,

I take it this is your first experience with object oriented design. I would recommend as you move forward that you research the MVC design pattern and look at frameworks such as Zend Framework that might lessen the learning curve for you.

Zend offers a PHP Framework with a great MVC implementation and full documentation.

Cheers.

Tommybs




msg:4020722
 9:53 pm on Nov 6, 2009 (gmt 0)

Are you actually referring to the $_GLOBAL array here and REGISTER_GLOBALS in php.ini? If you have register_globals turned off I'm not sure what you're actually worried about here. Are you worried about someone altering $session via a $_GET parameter or the like?

rocknbil




msg:4021024
 5:12 pm on Nov 7, 2009 (gmt 0)

Welcome aboard bpejman . . .

I think the original post is asking how to access variables from multiple locations without making it a global to avoid something like

function foo() {
global $myvar;
}

Not in the context of security (although the word is used,) in the context of good PHP coding practices.

This is actually something I don't fully grok myself, I've read the articles, read why you shouldn't use globals, know how to create classes, but sometimes get cornered into using global variables myself.

<awaiting answers as well> :-)

Tommybs




msg:4021046
 7:24 pm on Nov 7, 2009 (gmt 0)

If you need to use the variable I guess it comes down to whether to pass it in to your function or constructor or to access the global version. In the case of your session you might want to perform an action on a user object.

I don't know what's considered the best, though if you are passing in a user object to manipulate would it work.

e.g.


function alterUser($user){
$user->name = $user->name." - test";
return $user;
}
versus
function alterUser(){
global $user;
$user->name = $user->name." - test";
} // Does this now need a return value?

Also in the top example, in you main file would you need to do

$user = myFunc($user);

in you file that calls the function to ensure that the user object is actually updated?

JohnCanyon




msg:4021084
 10:04 pm on Nov 7, 2009 (gmt 0)

I think the original post is asking how to access variables from multiple locations without making it a global to avoid something like..

If this is the case, you should look into the Singleton pattern. A quick example is below:


class DataRegistry {

public static $instance = null;
private $data;

private function __construct() {}

public static function instance() {
if(is_null(self::$instance) {
self::$instance = new DataRegistry();
}
return self::$instance;
}

public function getData($value) {
$inst = self::instance();
if(isset($inst->data[$value])) {
return $inst->data[$value];
}
return null;
}

public function setData($key, $value) {
$inst = self::instance();
$inst->data[$key] = $value;
}
}

Usage:

$registry = DataRegistry::instance();
$registry->setData('var', 'myValue');
echo $registry->getData('var');

Should see: myValue

This class can be called from anywhere within your application and will always hold the same values (unless of course you overwrite them).

So, you could have a function...

function doSomethingUseful() {
//get Registry Value
$registry = DataRegistry::instance();
$registry->getValue('var'); //will be myValue
}

If the data needs to persist simply modify your data registry to add session handling.

Cheers.

bpejman




msg:4022876
 3:44 am on Nov 11, 2009 (gmt 0)

rocknbil, that's exactly what I'm looking for. The idea is to not use global variables. So, here's what I've concluded based on everyone's input and John's singleton class and by the way, thanks to everyone for their input.

/* index.php file */

// need to trigger it somehow
doSomethingUseful();

function doSomethingUseful()
{
// $registry variable now has a limited scope
// instead of it being global

$registry = DataRegistry::instance();
$registry->getValue('var');
}

class DataRegistry {
//use of "static" is important. Thanks!
...
};

I hope this is a better approach than just doing

$registry = DataRegistry::instance();

outside of the DataRegistry class inside of index.php.

Thanks,
Bobby

JohnCanyon




msg:4022930
 6:14 am on Nov 11, 2009 (gmt 0)


I hope this is a better approach than just doing

$registry = DataRegistry::instance();

outside of the DataRegistry class inside of index.php.

The important concept to understand here is that you are utilizing a singleton class. This means, that you can share the same instance of that class throughout o your application whether it be other classes or functions.

If you need limited scope, than a singleton class would be overkill, if you need a variable to only be valid within a class instance, the singleton class would be overkill.

Anyway, glad you found a solution that works for you.

Cheers.

bpejman




msg:4023842
 4:03 pm on Nov 12, 2009 (gmt 0)

I just realized something...

While the Singleton pattern is wonderful by forcing only one instance of a class to exist, how would that be beneficial for websites because each page request in a website triggers an instance so it's essentially the same as a normal class. I think this is perfect if and when the instance of the singleton class can be passed from one page to another.

If I'm understanding this correctly, I think one can store this instance either in a Text file, Database or a Session variable using Serialize()/UnSerialize().

The problem with text files and databases are the overhead for each page request. What about $_SESSION? Is it safe to use it there instead?

I guess, what's the best way of keeping a session persistent?

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved