简体   繁体   中英

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".

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.

Code In 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)

<?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.

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?

SCOPE OF THE PROJECT

The main.php code is being placed 'inside' of another php variable that is being used to create a webpage. 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\\']; ?> .

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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