开发者

Is there a way to reference a variable from an external document with PHP?

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 wo开发者_JAVA技巧rked";

Is there any possible way to do something like this?


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.


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!";
    }
?>


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.


Do

include('external.php');

then $variable contains the string "true".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜