Is there any way to access variable in other files inside PHP function?

James David Deann Source

I'm trying to access to variables in other files within a php function. outside of the function it brings the value that i want without problems but i don't know why if i try to access to the variable inside the php function, i can't access the value.

i have a file called name.php

<?php 
$name1 = "aa";
$name2 = "bb"; 
?>

and in index.php i'm trying to access to the variables in name.php like this.

<?php
include_once('name.php');
echo $name1;


name();
function name(){
echo $name1;
}

?>

as i said i can print the name1 variable outside the function but not inside. can i know why and how to access to the variables in this case?

Thank you

phpfunctionvariables

Answers

answered 3 months ago Raf A. #1

Use global $name; inside function

Read more about globals Variable.

answered 3 months ago jun drie #2

You can use Global variable or you can add parameter to your function to pass the value.

By using Global:

echo name();
function name(){
  global $name1, $name2;
  echo $name1;
}

By Adding function parameter:

echo name($name1);
function name($name1){
  echo $name1;
}

answered 3 months ago pyrsmk #3

Your problem comes from a basic of PHP : the scope of functions is local, not global, contrary to JavaScript.

You could use globals to achieve what you want to do, but I strongly discourage you to use them.

To me, your best shot is to pass your variables directly to your function, or to use closures.

// Example 1 : pass variables to the function
function name($name1) {
    echo $name1;
}

// Example 2 : use a closure
$myNameFunc = function() use($name1) {
    echo $name1;
};

You can read more about closures from the PHP documentation.

answered 3 months ago VTodorov #4

In PHP (and many other languages) the variables are visible only in the scope in which they are defined. In your example:

<?php 
$name1 = "aa";
$name2 = "bb"; 
//this is the *global* scope
?>


<?php
include_once('name.php');
echo $name1; // you are still in the global scope so $name1 is defined


name();
function name(){
echo $name1; // here you are in the name() function scope. The variable $name is not defined here
}

?>

There are 2 ways to access variables from the global scope inside a function. One them is using the keyword global when defining your variable. That makes the variable visible inside all scopes which are inside the "global" scope. That is not recommended since the variable will be visible in scopes in which you don't need it (and other reasons maybe someone could explain better).

The best thing you can do is to pass your variable as a parameter to your function.

You can define the function like this:

function name($param){
    echo $param;
}

And later call your function like this:

name($name1);

comments powered by Disqus