CudoX
CudoX

Reputation: 1003

php variable not detected

im having trouble with my php program, it seems that my array variable being declared earlier wasn't detected in a function. Here's my code :

$msg = array(
//Errors List
'Error1' => 'Error 1', 
'Error2' => 'Error 2'
);

//Class for outputting Messages
class Message {
    static function Info($string) { echo $string; }
    static function Error($string) { echo $string; }
}

//Functions
function function1($var1) {
    if (!preg_match("/^[0-9]+$/", $var1)){
        Message::Error($msg['Error1']);
    }

when i run it, and example i test the program like this..

$test = 'blabla';
function1($test);

it says the msg variable was undefined. Can anyone tell me how to resolve this? Thanks in advance.

Upvotes: 0

Views: 224

Answers (2)

fvu
fvu

Reputation: 32953

There are three ways to solve this issue.

Passing the required global var as a parameter

In my opinion, this is the preferred solution, as it avoids the pollution of your function with global variables. Global variables tend to introduce unexpected side effects and make maintenance and reuse of code a lot harder. A very extensive article on why you should avoid globals whenever possible (and some alternative solutions) can be found in the c2 wiki

function function1($var1,$mesg) {
    if (!preg_match("/^[0-9]+$/", $var1)){
        Message::Error($mesg['Error1']);
    }
}

The call to function1 changes to

function1($test,$msg);

Using global:

Same effect as the one just below, other notation.

function function1($var1) {
    global $msg;

    if (!preg_match("/^[0-9]+$/", $var1)){
        Message::Error($msg['Error1']);
    }
}

Using the $GLOBALS superglobal

Some sources say this form is slightly faster than the one using global

function function1($var1) {
    if (!preg_match("/^[0-9]+$/", $var1)){
        Message::Error($GLOBALS['msg']['Error1']);
    }
}

Upvotes: 3

Harish Singh
Harish Singh

Reputation: 3329

you can not use $msg as a local variable in function.

function function1($var1) {
    global $msg;

    if (!preg_match("/^[0-9]+$/", $var1)){
        Message::Error($msg['Error1']);
    }
}

Upvotes: 0

Related Questions