Jump to content

Global Variables and function arguments?


mds1256

Recommended Posts

Hello

 

I've have read that global variables should not be used.

 

so if i have 2 .php files:

 

index.php    -  main content php file

 

sitefunctions.php    -    php functions site file

 

 

 

on my index.php page i have the following (an example of my problem):

 

<?php

displayError($errorID);

?>

 

 

and in the sitefunctions.php file i have the following (an example of my problem):

 

 


<?php

function displayError($errorID)
{
        if($errorID == 1)
        {
              echo "Password Failure";
        }
        else
        {
              echo "Other Failure";
        }
}

?>

 

 

now that works but since when first accesing that page the $errorID is not set then i get an error. How can i achieve this without first setting a blank $errorID global variable?

 

Thanks

 

 

Link to comment
https://forums.phpfreaks.com/topic/225716-global-variables-and-function-arguments/
Share on other sites

Over to what?

 

I think you're confusing variables in the global namespace (which was, until very recently, the de facto namespace for everything in PHP) and the use of the 'global' keyword.

 

Pass variables into functions through their argument lists, and take care that they are defined (read: have a value) before attempting to use them.

so i take it that 0 will be a default but what happens then if it is declared, will it take the declared errorID rather than the 0?

 

no. you have to SEND the value to the function when it's called. if you don't send a variable, the default 0 will be used.

 

// something causes an error, so you set the error id before calling the function
$error_id = 123;

// Call the function, passing the value
displayError($error_id); // Note: the name of the passed variable is ignored by the function, so it can be anything.

so i take it that 0 will be a default but what happens then if it is declared, will it take the declared errorID rather than the 0?

 

no. you have to SEND the value to the function when it's called. if you don't send a variable, the default 0 will be used.

 

// something causes an error, so you set the error id before calling the function
$error_id = 123;

// Call the function, passing the value
displayError($error_id); // Note: the name of the passed variable is ignored by the function, so it can be anything.

 

thanks! thats what im after! :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.