开发者

HTML/PHP Variable passing

开发者 https://www.devze.com 2023-03-12 01:00 出处:网络
I\'m still kinda new to HTML/PHP and wanted to figure out how to streamline my pages a little bit more. I want to try to pass a variable from the page I include another PHP file on.开发者_开发技巧

I'm still kinda new to HTML/PHP and wanted to figure out how to streamline my pages a little bit more. I want to try to pass a variable from the page I include another PHP file on.开发者_开发技巧

For example:

    <?php include "quotes.php";  $name='tory'?>

I then want to use this variable name, $name='tory', in my quotes.php file. I'm unsure if I'm going about this the correct way because if I try to use the variable $name in my quotes.php file, it says that "name" is undefined.

Question has been answered. Needed to switch the statements. Thank you all!


Assign $name variable before including other files:

<?php
$name='tory';
include "quotes.php";
?>


Reverse it:

<?php $name='tory'; include "quotes.php"; ?>


You cannot use a variable before it was declared.

In your example, you're including quotes.php before the $name variable declaration, it will never work.

You can do

<?php $name='tory'; include "quotes.php"; ?>

Now, $name exists in "quotes.php"


What you're doing isn't necessarily the best way to go about it, but to solve your specific problem, simply define the variable before including the file. Then the variable will be globally scoped and available in the include file.

<?php
   $name = 'tory';
   include "quotes.php";
?>


You need to define $name first before including quotes.php.


You have to declare the variable $name before including the file.

<?php
    $name = 'tory';
    include 'quotes.php';
?>

This makes sense because the file you included will get parsed and executed and then move on with the rest.


The statements are executed in sequence. It is as though you had copy-and-pasted the contents of quotes.php at the point in your script where the include statement is found. So at the point where you execute quotes.php, the statement defining $name has not happened yet. Therefore to get the behaviour you want, you should reverse the order of the two statements.

0

精彩评论

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