I'm pretty new to php and I've read many times "avoid global variables" but I've not understood whether I have to follow this advice everytime or not.
I need some values (they are stored into two variables) into a function and I could put both variables as parameters:
$GVar1 = array(...); //This is a multidimensional array (over 80.000 chars in declaration)
$GVar2 = array(...);
$Result = DoMyStuff('BasicValue', $GVar1, $GVar2);
function DoMyStuff ($BasicParameter, $GV1, GV2){
//Do stuff
}
or declare variables as global into the function:
$GVar1 = array(...);
$GVar2 = array(...);
$Result = DoMyStuff('BasicValue');
function DoMyStuff ($BasicParameter){
global $GVar1;
global $GVar2;
//Do stuff
}
I would like to understand if the first way is really better .. and why?
I am a still a newbie when it comes to using YII, but I been working with session variables for the past few days, and I can't seem to grasp to the concept behind my error. Any advice will be appreciated.
My add function works perfectly so far, for my current purpose of keeping track of the last 3 variables added to my session variable nutrition.
public function addSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
Yii::app()->session['nutrition'] = array();
}
$nutrition = Yii::app()->session['nutrition'];
array_unshift($nutrition, $pageId);
array_splice($nutrition, 3);
Yii::app()->session['nutrition'] = $nutrition;
}
My remove function doesn't seem to work at all, no matter what I try to do with it. The reason why I am transfering the session array to a temp array was to try to get around the "If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called." But it was a total failure.
public function removeSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
return true;
}
$nutritionArray = Yii::app()->session['nutrition'];
unset($nutritionArray[$pageId]);
Yii::app()->session['nutrition'] = $nutritionArray;
}
Any advice or push toward to the correct direction will be appreciated.
I personally I have never used Yii::app()->session I normally use the Yii user and I have never had any issues with it:
Yii::app()->user->setState('test', array('a'=>1,'b'=>2));
print_r(Yii::app()->user->getState('test')); //see whole array
$test = Yii::app()->user->getState('test');
unset($test['b']);
Yii::app()->user->setState('test',$test);
print_r(Yii::app()->user->getState('test')); //only 'a'=>1 remains
Yii::app()->user->setState('test', null);
print_r(Yii::app()->user->getState('test')); //now a null value
As I put in a comment above there seems to be issues with multidimensional arrays with the session variable: https://code.google.com/p/yii/issues/detail?id=1681
Before going into the details of this question, I'd like to point out that I have never seen this done before, and would be rather curious to see if it can actually be done, and if so, how to go about doing it.
I'm currently sitting on a template loader, and to write it, I have chosen to slightly adapt the HAML file format and extend it with a couple of logic operators - loops, mostly. To do so efficiently, I'd need to pass a list of parameters to the template parser...and I'd prefer to avoid this if possible. While brainstorming for alternatives, the idea came around that maybe, just maybe, it would be possible to reference the scope in which the function was called.
Currently, I'm calling the template parser for a file as follows. Suppose test() is a route.
function test() {
$q = $UserModel->tether($userID)->fetchPermissions();
Util::Templating()->parse("file.haml");
}
What I'm trying to avoid is being able to access $q without passing a massively long array as second parameter. My original thought was that there might be a way for parse() to inherit the scope in which it was originally called (here, inside test) rather than having its own. Is there a way to manage this, and if so, how efficient is it?
Includes the superglobals as well:
$a = 'Hello World';
$b = range('A','Z');
$scopeVars = get_defined_vars();
var_dump($scopeVars);
test($scopeVars);
function test($scopeVars) {
extract($scopeVars);
echo '$a = '; var_dump($a);
echo '$b = '; var_dump($b);
}
EDIT
Just as an experiment, to eliminate the superglobals:
$a = 'Hello World';
$b = range('A','Z');
$scopeVars = get_user_defined_vars(get_defined_vars());
test($scopeVars);
function test($scopeVars) {
extract($scopeVars);
echo '$a = '; var_dump($a);
echo '$b = '; var_dump($b);
}
function get_user_defined_vars($vars) {
return array_diff_key(
$vars,
array_flip(
array('_SERVER','_GET', '_POST', '_REQUEST', '_FILES', '_COOKIE', '_ENV')
)
);
}
But removing the superglobals does seem to make it a bit slower
So i think creating a view object setting it properties and than passing it could work. Or instead of object work with array directly. e.g:
function test() {
$params = array();
$params['var_1'] = 'qwe1';
$params['var_2'] = 'qwe2';
$params['var_3'] = 'qwe3';
$params['var_4'] = 'qwe4';
$params['q'] = $UserModel->tether($userID)->fetchPermissions();
Util::Templating()->parse("file.haml", $params);
}
I am trying to define dynamically variables. I am using a function for this, but I don't know how to define the new var as global (because it never created before the function).
is that possible ?
Thanks.
edit
ok, this is what I've built. is it that dangerous ?
function extract_values($row) {
foreach ($row as $key => $value){
global $$key;
$$key = $value;
}
}
and then I'm trying to make my life easier like that:
$result = mysql_query("SELECT first_name, last_name, address FROM users ORDER BY id ASC");
while ($row = mysql_fetch_array($result)){
extract_values($row);
#[do some stuff with the variables.]#
}
I am doing it to save time. instead of creating for each column it's own variable like
$first_name = $row['first_name'];
This function does that for me.
I don't see why in this case it might be dangerous..
or as usuall, i am missing something..
Try this:
function doSomething() {
global $x;
$x = 5;
}
If you prefer to save a couple of bytes, you can use the $_GLOBALS array for this:
$_GLOBALS['x'] = 5;
Regarding your edit: It makes your code less understandable.
Actually, there already exists a function that is doing this: extract().
while (($row = mysql_fetch_assoc($result))){
extract($row);
// ...
}
extract() is even better, because it lets you specify what should happen if the variable already exists and/or lets you specify a prefix (so you don't overwrite already existing variables with that name). E.g. you could do:
extract($row, EXTR_PREFIX_ALL, 'db');
which would result in $db_first_name etc.
Surly, extract() is also doing some internal work here, but using built-in functions is always better than creating your own.
Another possibility would be to use list():
while (($row = mysql_fetch_row($result))){
list($first_name, $last_name, $address) = $row;
// ...
}
You can do it in two ways:
Make the variable global using the global keyword:
function fun1() {
global $foo;
$foo = 1;
}
Alternatively you can also create an new element in the $GLOBALS array:
function fun2() {
$GLOBALS['bar'] = 1;
}
Working code
Remember that these are considered bad practice, a function should have local variables invisible outside and should get inputs through the arguments passed. You should avoid getting arguments though global variables and must completely avoid crating global variables.
Anyone has an idea if this is at all possible with PHP?
function foo($var) {
// the code here should output the value of the variable
// and the name the variable has when calling this function
}
$hello = "World";
foo($hello);
Would give me this output
varName = $hello
varValue = World
EDIT
Since most people here 'accuse' me of bad practices and global variables stuff i'm going to elaborate a little further on why we are looking for this behaviour.
the reason we are looking at this kind of behaviour is that we want to make assigning variables to our Views easier.
Most of the time we are doing this to assign variables to our view
$this->view->assign('products', $products);
$this->view->assign('members', $members);
While it would be easier and more readable to just be able to do the following and let the view be responsible to determining the variable name the assigned data gets in our views.
$this->view->assign($products);
$this->view->assign($members);
Short answer: impossible.
Long answer: you could dig through apd, bytekit, runkit, the Reflection API and debug_backtrace to see if any obscure combination would allow you to achieve this behavior.
However, the easiest way is to simply pass the variable name along with the actual variable, like you already do. It's short, it's easy to grasp, it's flexible when you need the variable to have a different name and it is way faster than any possible code that might be able to achieve the other desired behavior.
Keep it simple
removed irrelevant parts after OP edited the question
Regardless of my doubt that this is even possible, I think that forcing a programmer on how to name his variables is generally a bad idea. You will have to answer questions like
Why can't I name my variable $arrProducts instead of $products ?
You would also get into serious trouble if you want to put the return value of a function into the view. Imagine the following code in which (for whatever reason) the category needs to be lowercase:
$this->view->assign(strtolower($category));
This would not work with what you're planning.
My answer therefore: Stick to the 'verbose' way you're working, it is a lot easier to read and maintain.
If you can't live with that, you could still add a magic function to the view:
public function __set($name, $value) {
$this->assign($name, $value);
}
Then you can write
$this->view->product = $product;
I don't think there is any language where this is possible. That's simply not how variables work. There is a difference between a variable and the value it holds. Inside the function foo, you have the value, but the variable that held the value is not available. Instead, you have a new variable $var to hold that value.
Look at it like this: a variable is like a bucket with a name on it. The content (value) of the variable is what's inside the bucket. When you call a function, it comes with its own buckets (parameter names), and you pour the content of your bucket into those (well, the metaphor breaks down here because the value is copied and still available outside). Inside the function, there is no way to know about the bucket that used to hold the content.
What you're asking isn't possible. Even if it was, it would likely be considered bad practice as its the sort of thing that could easily get exploited.
If you're determined to achieve something like this, the closest you can get would be to pass the variable name as a string and reference it in the function from the $GLOBALS array.
eg
function this_aint_a_good_idea_really($var) {
print "Variable name: {$var}\n";
print "Variable contents: {$GLOBALS[$var]}\n";
}
$hello="World";
this_aint_a_good_idea_really('hello');
But as I say, that isn't really a good idea, nor is it very useful. (Frankly, almost any time you resort to using global variables, you're probably doing something wrong)
Its not impossible, you can find where a function was invoked from debug_backtrace() then tokenize a copy of the running script to extract the parameter expressions (what if the calling line is foo("hello $user, " . $indirect($user,5))?),
however whatever reason you have for trying to achieve this - its the wrong reason.
C.
Okay, time for some ugly hacks, but this is what I've got so far, I'll try to work on it a little later
<?php
class foo
{
//Public so we can test it later
public $bar;
function foo()
{
//Init the array
$this->bar = array();
}
function assign($__baz)
{
//Try to figure out the context
$context = debug_backtrace();
//assign the local array with the name and the value
//Alternately you can initialize the variable localy
//using $$__baz = $context[1]['object']->$__baz;
$this->bar[$__baz] = $context[1]['object']->$__baz;
}
}
//We need to have a calling context of a class in order for this to work
class a
{
function a()
{
}
function foobar()
{
$s = "testing";
$w = new foo();
//Reassign local variables to the class
foreach(get_defined_vars() as $name => $val)
{
$this->$name = $val;
}
//Assign the variable
$w->assign('s');
//test it
echo $w->bar['s'];
}
}
//Testrun
$a = new a();
$a->foobar();
impossible - the max. ammount of information you can get is what you see when dumping
debug_backtrace();
Maybe what you want to do is the other way around, a hackish solution like this works fine:
<?php
function assign($val)
{
global $$val;
echo $$val;
}
$hello = "Some value";
assign('hello');
Ouputs: Some value
What you wish to do, PHP does not intend for. There is no conventional way to accomplish this. In fact, only quite extravagant solutions are available. One that remains as close to PHP as I can think of is creating a new class.
You could call it NamedVariable, or something, and as its constructor it takes the variable name and the value. You'd initiate it as $products = new NamedVariable('products', $productData); then use it as $this->view->assign($products);. Of course, your declaration line is now quite long, you're involving yet another - and quite obscure - class into your code base, and now the assign method has to know about NamedVariable to extract both the variable name and value.
As most other members have answered, you are better off suffering through this slight lack of syntactic sugar. Mind you, another approach would be to create a script that recognizes instances of assign()'s and rewrites the source code. This would now involve some extra step before you ran your code, though, and for PHP that's silly. You might even configure your IDE to automatically populate the assign()'s. Whatever you choose, PHP natively intends no solution.
This solution uses the GLOBALS variable. To solve scope issues, the variable is passed by reference, and the value modified to be unique.
function get_var_name(&$var, $scope=FALSE) {
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = 'unique'.rand().'value';
$vname = FALSE;
foreach ($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
$testvar = "name";
echo get_var_name($testvar); // "testvar"
function testfunction() {
$var_in_function = "variable value";
return get_var_name($var_in_function, get_defined_vars());
}
echo testfunction(); // "var_in_function"
class testclass {
public $testproperty;
public function __constructor() {
$this->testproperty = "property value";
}
}
$testobj = new testclass();
echo get_var_name($testobj->testproperty, $testobj); // "testproperty"