0

this is probably a basic question about php, but I can't figure out how to solve it.

Well, I have a file called globals.php

<?php
$DATA = array(
    'first' => 'LOL',
    'second' => 'Whatever'
);
?>

And I also have another file (omg.php) with the following function:

<?php

require_once('globals.php');

function print_text_omg($selector = 0){
global $DATA; //added this line of code. NOW IT WORKS
$var = '';
if($selector == 0){
    $var = '';
}else{
    $var = 'Hi. ';
}

//$DATA is a variable from globals.php that is supposed to be declared in require_once('globals.php');
//$var is a variable inside the function print_text_omg
//I am trying to concatenate string $var with the string $DATA['first']

$finaltext = $var.$DATA['first'];
echo $finaltext;
}
?>

Then, in main.php I have this:

<?php 
include('omg.php');
print_text_omg();
print_text_omg(1);
?>

This should print something like:

//LOL
//Hi. LOL

Instead, I have this warning:

Notice: Undefined variable: DATA in ...

Which is the part of $finaltext = $var.$DATA['first'];

UPDATE

Thanks to user Casimir et Hippolyte' suggestion, I've edited my function and it works now. Added the line that worked for me.

3 Answers 3

1

It doesn't work because $DATA isn't in the scope of your function.

To make $DATA available inside your function, you must pass it as a parameter to the function or define $DATA as a global variable.

The problem isn't related to require_once.

http://php.net/manual/en/language.variables.scope.php

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

2 Comments

THANK YOU, I've added global $DATA; to my function and it worked perfectly.
@mgXD-2: be careful, using globals denotes a conception problem (most of the time) and is considered as a bad practice (The good practice is to allow the access to an information only to concerned elements). It is better to add a parameter to your function, or to build a class where $DATA is a static variable and your function a method of the class. (but I think you will test this last way later).
0

The error is correct, first I can't find where did you declare $var (maybe it should be an object of some class?) and also $var doesn't contain the $DATA array, and for last, . operator in php is for concatenate strings, for object navigation is -> operator

Comments

0

You haven't declared the variable $var, plus . is php's concatenation operator. Try changing your code to this

$finaltext = $DATA['first'];

Comments

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.