Jump to content

Recommended Posts

Hi everyone, hope u can help me with this question.

 

I have a file where i keep variables and I also have a function where i need to use these variables, but when inside the function the variables are undefined.

 

Notice: Undefined variable: bla bla bla

 

I use the variables file as an include

How can I use these variables inside the functions without redefining them? Thanks in advance, any answer is appriciated.

Link to comment
https://forums.phpfreaks.com/topic/43539-solved-undefined-variable/
Share on other sites

Are the variables you use in the function defined outside of the function?

 

if they are then this is why. Functions have there own variable scope. Functions cannot use functions that was defined outside of it, unless they passed as a parameter to the function or you define the variables as global when you set the function.

 

Examples:

Global

<?php

$myvar = 'hello world';

function myfunc() {
    global $myvar; // myvar is now global

    echo $myvar;
}

myfunc();

?>

Parameter

<?php

$myvar = 'hello world';

function myfunc($var1) {
    // $var is a parameter. Functions can have multipl parameters.
    // each parameter is separated by a comma.
    echo $var1;
}

myfunc($myvar);

?>

Thank you guys. The only problem is that the variables file is like a language file and has like hundreds of vars. And I need to use like 50 variables inside the function. Do I need to global all of them one by one. Is there any faster way. The variables file is external. Thank you

I would put them into an array and just pass that array. That or if it is language, define them as constans IE:

 

define('LANG_VAR1', "Display this text");
define('LANG_VAR2', "Display this text");
define('LANG_VAR3', "Display this text");

 

That way they are available for any function throughout the site.

np, If you were really ambitious about it (I had the same problem a while ago) I created a script to parse the php file and create the constants from that without having to re-type everything =)

 

Once that is done, incase you ever need it again you have the script.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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