简体   繁体   English

是否可以在包含PHP的文件中使用PHP主页面中的PHP变量?

[英]Is it possible to use a PHP variable from the main php page in an php included file?

I have a "main" php webpage called "main.php" and I have an included file called "comments.php". 我有一个名为“ main.php”的“主要” php网页,并且包含一个名为“ comments.php”的文件。

In main.php I'm using the following to get the url of the page, but I'm trying to use the $shareURL variable in the included file (comments.php) and it isn't working. 在main.php中,我使用以下命令获取页面的url,但是我尝试在包含的文件(comments.php)中使用$ shareURL变量,但该命令不起作用。

Code In Main.php Main.php中的代码

<?php $shareURL = "http://".$_SERVER[\'SERVER_NAME\'] . $_SERVER[\'REQUEST_URI\']; ?>

Above is the variable. 上面是变量。 Below is the include. 以下是包含。

<?php include "$domainName/assets/includes/fbCommentBox.php"; ?>

Code in the Include File (comment.php) 包含文件(comment.php)中的代码

<?php echo "<div class='fb-comments' data-href='$shareURL' data-num-posts='5' data-width='100%'></div>"; ?>

If I use the above in my included file, I get the pages URL for the include file, not the main.php page. 如果在包含文件中使用上述内容,则将获得包含文件的页面URL,而不是main.php页面。

Is there a method to use a php variable within the main.php page that will pass its value into the included (comments.php) file? 是否有一种方法可以在main.php页面中使用php变量,将其值传递到包含的(comments.php)文件中?

SCOPE OF THE PROJECT 项目范围

The main.php code is being placed 'inside' of another php variable that is being used to create a webpage. main.php代码被放置在另一个用于创建网页的php变量的“内部”。 I need the \\ in <?php $shareURL = "http://".$_SERVER[\\'SERVER_NAME\\'] . $_SERVER[\\'REQUEST_URI\\']; ?> 我需要\\<?php $shareURL = "http://".$_SERVER[\\'SERVER_NAME\\'] . $_SERVER[\\'REQUEST_URI\\']; ?> <?php $shareURL = "http://".$_SERVER[\\'SERVER_NAME\\'] . $_SERVER[\\'REQUEST_URI\\']; ?> <?php $shareURL = "http://".$_SERVER[\\'SERVER_NAME\\'] . $_SERVER[\\'REQUEST_URI\\']; ?> . <?php $shareURL = "http://".$_SERVER[\\'SERVER_NAME\\'] . $_SERVER[\\'REQUEST_URI\\']; ?>

Example

<?php
$content = ' 
<?php $shareURL = "http://".$_SERVER[\'SERVER_NAME\'] . $_SERVER[\'REQUEST_URI\']; ?>
';
?>

A better [than globals], though possibly more involved, approach would be to have all the code in the included file wrapped in functions or in a class, and then passing the variable into those functions when you call them from the main file. 一种比全局变量更好的方法,尽管可能涉及更多的方法,是将包含文件中的所有代码包装在函数或类中,然后在从主文件调用它们时将变量传递给这些函数。

EDIT: Removed my suggestion of using global , per the comment below. 编辑:根据以下评论,删除了我使用global建议。 global only applies if you are sharing a variable between scopes, ie between one function and another or between a function body and the global space. global仅适用于在范围之间(即一个函数与另一个函数之间或函数体与全局空间之间)共享变量的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM