0

So, I have two php functions:

function RADD_FILE_GLOBAL(){
   ...
   $file_att = implode(",",$files); 
}

I need to access this $file_att variable from another function:

function FILE_NAME(){
 // need $file_att here
}

How do I access a variable from another function?

5
  • you can define this variable as global Commented Feb 19, 2016 at 9:28
  • You could pass it in as a parameter Commented Feb 19, 2016 at 9:31
  • @Dezza, for passing this parameter inside function, you need to call second function inside first function. so why don't you declare it as global? Commented Feb 19, 2016 at 9:32
  • @MahaDev global var is not a good practice, of course it has its benefits, but not in this case. Commented Feb 19, 2016 at 9:37
  • use class/oop concept. Commented Feb 19, 2016 at 9:39

3 Answers 3

3

You could set a return value from the first function which could either be passed as a parameter to the second function or declared, within the second function, as a global.

function RADD_FILE_GLOBAL(){
    /* other code */
   $file_att = implode(",",$files);
   return $file_att; 
}
function FILE_NAME( $file_att ){
    /* do something with variable */
}
/* or */
function FILE_NAME(){
    global $file_att;
    /* do something with var */
}

/* run first function, return a value */
$file_att=call_user_func( 'RADD_FILE_GLOBAL' );

/* later */
call_user_func( 'FILE_NAME',$file_att );
Sign up to request clarification or add additional context in comments.

Comments

2
$file_att = '';

function RADD_FILE_GLOBAL(){
   global $file_att;
   ...
   $file_att = implode(",",$files); 
}

function FILE_NAME(){
    global $file_att;
 // you have now $file_att here
}

Comments

-1

You could use global but it's a bit ugly and totally useless. The best way is what @Dezza says, pass it as a parameter :

function RADD_FILE_GLOBAL(){
   $file_att = implode(",",$files); 
   $file_name = FILE_NAME($file_att);
}

function FILE_NAME($file_att){
    // use $file_att
}

3 Comments

Then call it from another function ? or from somewhere else ? You have to call the function at one moment...
But this updated variable will not be available outside of this function if you call from somewhere else.
Well the original question was how to use a variable from another function not how to store a result globally.

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.