user1452926
user1452926

Reputation: 28

when including a file using php function not work?

MY PHP FUNCTION IS

function functionName()
{
include($_SERVER['DOCUMENT_ROOT']."/path/file.php");
}

Content of File.php is

$foo = 'bar';

Calling function (content of file test.php)

functionName();

When call function and variable not work

echo $foo;  <- not works

But when adding code below its works (content of file test.php)

include($_SERVER['DOCUMENT_ROOT']."/path/file.php");
echo $foo; <- its works

Upvotes: 0

Views: 84

Answers (3)

user1078781
user1078781

Reputation:

function functionName()
{
global $foo;
global $bar;

include($_SERVER['DOCUMENT_ROOT']."/path/file.php");
}
functionName();
echo $foo;
echo $bar;

Upvotes: 0

Meki
Meki

Reputation: 395

All variables handled in a function are limited only to that function. You can create numberless variables in a function but these variables won't be available to you outside the function except the return variable.

function thisIsMyFunction () {
  $var1 = "foo";
  $var2 = "bar";
  return $var1;
}

echo thisisMyFunction();

Will give you "foo" which you can put in a variable or echo out. If you're looking for a way to load multiple variables for example a config file you could do the following:

config.php
$config["var1"] = "foo";
$config["var2"] = "bar";

index.php
include "config.php";

function myFunction(){
  global $config;
  echo $config["var1"] . " " . $config["var2"];
}

myFunction();

will result in

foo bar

So in short, something done in the function stays in the function unless some output of that function isn't defined. This is why including with a function will not work.

Upvotes: 3

ionFish
ionFish

Reputation: 1024

That's because if you don't include the other file, where $foo is defined, it can't just make up values for it.

But when adding include("/path/file.php"); its works.

Of course it does. Now, an important thing: Are you including based off of the domain name?

Example: http://www.site.com/path/to/file.php would include from http://www.site.com/path/file.php in the current setup. Here's how includes work:

  1. /file.php >> file is in the domain's root. HAS TO BE in domain's root.
  2. ./file.php >> file is in the same directory.
  3. ../file.php >> file is in the parent directory.
  4. ../../file.php >> file is in the grandparent directory.

(and so forth).

What include() and require() and their related functions do, is include another file as if it were part of the file that's including them. Here are the differences:

Include and require are identical, except upon failure:

  • require will produce a fatal error (E_COMPILE_ERROR) and the script will kill itself
  • include will only produce a warning (E_WARNING) and the script will finish the rest of the commands

Upvotes: 1

Related Questions