1

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!

7 Answers 7

6

Assign $name variable before including other files:

<?php
$name='tory';
include "quotes.php";
?>
Sign up to request clarification or add additional context in comments.

2 Comments

it should be noted that this is pretty bad design though!
This is not bad design at all if the goal of quotes.php is to to be a template.
3

Reverse it:

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

Comments

3

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"

Comments

3

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

Comments

2

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

Comments

2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.