有没有办法使用 PHP 从外部文档引用变量?

发布于 2024-08-19 04:19:14 字数 295 浏览 9 评论 0原文

我想使用 PHP 做一些小事情,但我需要知道如何从外部文档(例如 external.php)获取变量并在 PHP 文档(internal.php)的函数中使用它。 我在想也许是这样的:

外部.php

$variable = "true";

代码 内部.php 代码

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

有没有可能的方法来做这样的事情?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

溺孤伤于心 2024-08-26 04:19:14

为此使用 include 函数。在internal.php中

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

注意:这对于配置文件或类或辅助函数的加载非常有用,但请尽量避免在源代码中的随机位置包含太多内容。这会使您的代码非常难以阅读。

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.

怪我入戏太深 2024-08-26 04:19:14

如果您想将包含文件中的特定值直接包含到当前文档中的变量中,您还可以包含一个返回该值的 PHP 文件。

例如

inc.phpindex.php

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

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

    if(isset($var) && !empty($var)) {
        echo "It worked!\n";
        echo "Value: {$var}";
    }
    else {
        echo "It failed!";
    }
?>

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!";
    }
?>
安静 2024-08-26 04:19:14

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.

海夕 2024-08-26 04:19:14

然后

include('external.php');

$variable 包含字符串“true”。

Do

include('external.php');

then $variable contains the string "true".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文