0

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.

2 Answers 2

3

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']);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

awesome. i might need these if ill make more functions.
0

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']);
    }
}

2 Comments

thank you very much. Ill flag this as the right answer in few mins. Thanks for the help!
this must be the worst possible "solution"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.