0

I'm making a script for changing e-shop prices. This is my settings panel (key variables)

// --- <SETTINGS PANEL> --- //
$safe_mode = true;
$safer_mode = false;
$safe_cycle = false;
$file_loc = 'cata.txt';
$skuindex = '1';
$nameindex = '2';
$priceindex = '0';
$rowdelimiter = '_';
$celldelimiter = '-';
// --- </SETTINGS PANEL> --- //

Later on I'm using my safe_mode variable here:

function updateit($pricus,$skus,$namef)
{
 if($safer_mode)
 {
 $querytoup = "UPDATE product SET margin = '', vat_id = '1', cost = '', price = '".$pricus."' WHERE sku LIKE '".$skus."' AND name LIKE '".$namef."';";
 }
 else
 {
  $querytoup = "UPDATE product SET margin = '', vat_id = '1', cost = '', price = '".$pricus."' WHERE sku LIKE '".$skus."' AND name LIKE '".$namef."%';";
 };
 echo('Establishing connection...<br>');
 updateexec($querytoup);
};

updateexec(); then executes a bit more complex function I don't want to paste here. The problem is that I'm getting this kind of error/notice:

Notice: Undefined variable: safer_mode in /var/www/doit.php on line 54

Line 54 is exactly the if($safer_mode) line. So where did I go wrong? I know this stuff happens when you declare a variable inside a loop/function that doesn't run under some conditions so it's undeclared, but I'm declaring $safe_mode outside any functions, the settings panel is in the beginning of the file. I'm not running any includes or requires. Thanks for any replies.

3
  • 1
    Each function has its own local variable scope. Anything declared outside isn't automatically mirrored into functions. Commented Jan 31, 2015 at 14:51
  • 1
    PHP scope isn't like JavaScript (I only guess familiarity with JS because of the ; after closing }, which is not used in PHP) Commented Jan 31, 2015 at 14:53
  • You would have to pass that variable as a parameter into the updateit() function. Commented Jan 31, 2015 at 14:53

1 Answer 1

0

Global variables are not defined inside functions in PHP. In order to use them, you have to declare them using the global keyword.

function updateit($pricus,$skus,$namef)
{
    global $safer_mode;
    if($safer_mode)
    {

In general, using global variables in functions is bad practice. It should be avoided in the majority of cases.

Sign up to request clarification or add additional context in comments.

3 Comments

But it's better to pass the variable as a value into updateit(). The global keyword should be avoided because it causes side effects that are very hard to spot (until something stops working because of a seemingly unrelated change somewhere else).
Again, I'm not defining it inside a function, but outside. I'm just using it in the function. Fixed it with passing the variable as a parameter, the weird thing is that it used to work on older versions of PHP.
You are right, I should have mentionned it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.