views:

59

answers:

4

Hi! I wanted to use PHP do do a little thing, but I needed to know how to get a variable from an external document (say external.php) and use it in a function in a PHP document (internal.php). I was thinking maybe something like this:

Code for external.php

$variable = "true";

Code for internal.php

if ($GETFROM{'/external.php'}['variable']) 
echo "It worked";

Is there any possible way to do something like this?

+7  A: 

Use the include function for that. In internal.php

include 'external.php';
if($variable)
{
    echo "It worked";
}

Note: This is great for configuration files or loading of classes or helper functions, but try to avoid too many includes in random places in your sourcecode. This can make your code very hard to read.

Daff
You might want to fix the syntax error
kemp
Ops, fixed. Thank you.
Daff
+2  A: 

Do

include('external.php');

then $variable contains the string "true".

Jan P.
+3  A: 

In addition to the correct answer already given, you could take a look at PHP classes and objects so that you can access data from external sources (classes) without the risk of messing up with duplicate variable names which could be overwritten with a simple include.

kemp
+4  A: 

If you want to include a specific value from an include file directly into a variable in your current document, you can also include a PHP file which returns the value.

For example:

inc.php

<?php
    return "Hello, world!";
?>

index.php

<?php
    $var = include "inc.php";

    if(isset($var) && !empty($var)) {
        echo "It worked!\n";
        echo "Value: {$var}";
    }
    else {
        echo "It failed!";
    }
?>
Atli
Downvoted because this code ist wrong. return statement can only be used in ca function and the include line just makes no sense.
Thomas
@Thomas. The code works perfectly. Try it if you have doubts. And please, at least RTFM before deciding somebody is wrong. *(http://php.net/include - Example #5)*
Atli
@Atli: agreed. This is a very good solution.
nickf
+1 to offset Thomas' downvote. @Thomas - The code isn't wrong, you are.
zombat
Corrected my vote and learned something new - sorry :-)
Thomas