Home > Software design >  PHP: use variable in other included file to change HTML Text
PHP: use variable in other included file to change HTML Text

Time:10-30

this is my first time using php and stackoverflow.
I have two php files: index.php and content.php
content.php includes the basic HTML of my site, no php yet
index.php runs on Apache Server and includes the basic php. While running, it should show the HTML from content.php

This is the needed information:
index.php:

<?php  
require "content.php";
$text='this is the text, that should be shown in the paragraph';

content.php:

 <p><?php echo $text; ?></p>

My problem is, that the content.php file has an error: Undefined variable '$text'
Both are in the same folder and index.php shows the HTML in the browser as it should
Only the paragraph doesn`t show up correctly yet
I appreciate your help

CodePudding user response:

You are getting error because your loading first content.php and defining variable after it. You need to do like:

$text='this is the text, that should be shown in the paragraph';
require "content.php";

CodePudding user response:

Computers in general do exactly what you tell them, in the order you tell them. So your code goes like this:

  1. Start running "index.php"
  2. require "content.php"; - start running "content.php"
  3. <p><?php echo $text; ?></p> - display whatever $text contains right now
  4. end of "content.php", carry on in "index.php"
  5. $text='this is the text, that should be shown in the paragraph'; - store a string in the variable $text

As you can see, at step 3, $text doesn't contain anything yet. By the time you assign it a value at step 5, it's too late.

"Stepping through" a program to find a bug like this is a vital skill as a programmer, and well worth practising.

  •  Tags:  
  • php
  • Related