tnw
tnw

Reputation: 13877

HTML/PHP Variable passing

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!

Upvotes: 1

Views: 233

Answers (7)

Hammerite
Hammerite

Reputation: 22340

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.

Upvotes: 1

Kevin
Kevin

Reputation: 5694

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.

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270617

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

Upvotes: 3

G&#233;rald Cro&#235;s
G&#233;rald Cro&#235;s

Reputation: 3849

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"

Upvotes: 3

Cfreak
Cfreak

Reputation: 19309

Reverse it:

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

Upvotes: 3

pdu
pdu

Reputation: 10413

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

Upvotes: 2

hsz
hsz

Reputation: 152216

Assign $name variable before including other files:

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

Upvotes: 6

Related Questions