Jump to content

Recommended Posts

I have reduced a process to function with a minimal list of global variables that are required.

For simplicity, I'll offer this:

If form1 is submitted, then global $a is necessary

If form2 is submitted, then global $x and global $z are necessary.

Rather than "register" all three, I wanted to use an IF statement to point to the specific globals necessary for the specified form input.

My attempts are unsuccessful.

$a = 123;
$x = "hello";
$z = "there";

function choose(){
global $formSelector;

if($formSelector == "form1") {
global $a; 
} else {
global $x; global $z;
}

//Test for result
echo $z;
if ($a == 123){
echo "bye bye";
}
echo "test result";
}

//Call function
choose();

Can I segregate the globals or is a single comprehensive list the only solution?

Edited by phppup
Typos
Link to comment
https://forums.phpfreaks.com/topic/315269-separate-global-variables-to-use/
Share on other sites

The minimal number of globals is 0. (And sorry to see your TAB key has broken. :) )

16 minutes ago, phppup said:

If form1 is submitted, then global $a is necessary

If form2 is submitted, then global $x and global $z are necessary.

But that aside,

  • If it is form1, $z is not defined.
  • If it isn't form1, $a is not defined.
  • $x is never used.

Bit of a mess really.

Per haps something like this...

<?php
$a = 123;
$x = "hello";
$z = "there";
$formSelector = 'form2';

function choose($val1, $val2='')
{
    //Test for result
    echo $val2;
    if ($val1 == 123){
        echo "bye bye";
    }
    echo "test result";
}

//Call function
if ($formSelector == 'form1') {
    choose($a);
} else {
    choose($x, $z);
}  
?>

 

@Barand per reply #1 ... You'll be happy to know that I know that's a mess.  But as you realized, it was meant to demonstrate what I was trying to accomplish.

As for reply #2, I will have to try it in my script, but I see that it should both solve the issue by calling the function differently in each case AND removed the use of forewarned globals.

(Somewhat of a tragedy really since I already made the list. LOL  But then, better code is best!)

Out of curiosity, of I were to attempt to group the clusters as globals, is it possible?

Again, I see the wisdom and (assumed) success in your method, but an still curious.

Thanks for the help.

 

 

if you are writing functions that contain application specific values/variables, such that you are constantly editing existing or creating new functions, this is a sign that your function code is not general-purpose, has the wrong responsibility, is actually part of your main code, and should not be inside of a function.

you shouldn't be writing out bespoke lists of variables for each different form you are processing. you should be using a data-driven design, where you have a data structure (database table, array) that defines the expected fields, validation rules, and processing for each form. you would then loop over the correct definition that matches the submitted form and use general-purpose logic to validate and process the form data.

I would appreciate some clarification (as I've actually never used arguments this way in functions).

Experimentation seems to have revealed that this portion of the code needs to include all the related variables.

function choose($x, $z)

And that this

choose($x, $z);

to call the function must match identically.

 

However, we have taken the argument a step further, and some clarity would be helpful.

 

In this example we are assigning the variables in the call, but the function arguments are ALL the sought results?

Similar to giving an alias tho the variable???

Not entirely sure what you're asking about, however it sounds like you're wondering about the variable names?  The names you assign in the function are irrelevant to the names (if any) or what you end up passing in when you call the function.

function choose($x, $z){
   //$x is whatever value is passed in first
   //$z is whatever value is passed in second.
}

You can pass in whatever variables you want when you call it, or just some static value and not a variable at all.  They don't have to have the same name (though it's common that they do since they usually represent some type of data).

$a = 1; 
$b = 3;
choose($a, $b); // $x = 1, $z = 3
choose(6, $a); // $x = 6, $z = 1

Any changes you make to $x and $z inside the function will not affect the original variable passed into it.  Generally that is the desired behavior, and you just return some value from the function as it's output.  If you have a specific need to change that behavior and want the original variables to be modified, then you must indicate that by declaring the parameter as a reference parameter using &.

function accumulate(&$x, $y){
    $x += $y;
}

$a = 1;
accumulate($a, 2);
echo '$a = '.$a; // $a = 3
accumulate($a, $a); 
echo '$a = '.$a; // $a = 6
accumulate($a, 5);
echo '$a = '.$a; // $a = 11

Don't use references unless you really have a specific need to.  They can get messy and cause you debugging headaches just like globals.

 

If you're wondering about the discrete variables vs array thing, the difference is instead of defining a bunch of variables as parameters, you just define one which receives an array of values.  So instead of this:

function doStuff($colA, $colB, $colC, $colD, $colE, $colF){
	//Do stuff with $colA, $colB, $colC, $colD, $colE, $colF
}
$row = $db->query($sql)->fetch();
doStuff($row['colA'], $row['colB'], $row['colC'], $row['colD'], $row['colE'], $row['colF']);

You'd do this:

function doStuff($row){
	//Do stuff with $row['colA'], $row['colB'], $row['colC'], $row['colD'], $row['colE'], $row['colF']
}
$row = $db->query($sql)->fetch();
doStuff($row);

It keeps the argument list smaller which is good, but more importantly it lets the function be responsible for accessing the data it needs rather than you having to hand it out individually.  If in the future you need to add something to doStuff that needs access to colZ, you won't have to go around your application updating all the function calls to include colZ.

 

@kicken 

Quote

If in the future you need to add something to doStuff that needs access to colZ, you won't have to go around your application updating all the function calls to include colZ.

The future is NOW (because that was one of my thoughts initially)

My data is being pulled from $my_array which is outside of the function (as opposed to inside a db).

So what would be the correct way of addressing the function (as per your last example)?

Ideally, I would re-populate the array with any amount of values and still be able to use the same function without having to re-work the structure.

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.