Log in

View Full Version : Resolved variables to class



ggalan
11-23-2011, 09:46 PM
i have a page which has some get variables and i include class file.
what is the best way to get the variables from the page into the class?

my page:


$myPage = $_GET['p'];
$userID = $_GET['id'];
require_once("./class/UploadHandler.php");


my class, UploadHandler.php:


class UploadHandler
{
function __construct($options = null) {
$path = './../' . $userID . '/'. $myPage;
}
}

traq
11-24-2011, 01:31 AM
<?php
class UploadHandler{
public function __construct($options=null){
global $myPage,$userID;
// ...
}

// OR pass them into the class when initialized //
public function __construct($options=null,$variables_from_global_scope){
$myPage = $variables_from_global_scope['myPage'];
$userID = $variables_from_global_scope['userID'];
// ...
}

// OR simply //
public function __construct($options=null){
$myPage = $_GET['p'];
$userID = $_GET['id'];
// ...
}
}

djr33
11-24-2011, 04:38 AM
Just to add some info: traq's last option is the clear answer because $_GET (and others like it) is a variable without scope-- you can always access it. So there's no difference in using that for a class instead of in the regular non-class code.

But if you ever need to get a variable you can use the global method as in traq's first example, or use this convenient trick:
$GLOBALS['any_variable_name']; //equivalent to $any_variable_name in global scope

The only other way to do it is as in traq's second example, passing the values directly to the class (via a function or the class instance creation line).

Finally, remember that these methods have different effects for whether the value is saved to the variable if you change it. If you pass a variable to the function or otherwise make a copy, it won't change it's global value. But if you use a global method it will change it throughout the entire script.