Home  >  Q&A  >  body text

How to use PHP templates correctly

I am new to PHP and currently reading the book "PHP for Absolute Beginners". The book is currently teaching about templating and using StdClass() objects to avoid naming conflicts.

I have a template file named page.php and a home page file named index.php.

My page.php code

<?php
return "<!DOCTYPE html>
<html>
<head>  
<title>$pageData->title</title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>
</head>
<body>
$pageData->$content
</body>
</html>";

My index.php

<?php
//this correctly outputs any errors 
error_reporting( E_ALL );
ini_set("display_errors", 1);

$pageData = new stdClass();

$pageData->title = "Test title";
$pageData->content = "<h1>Hello World</h1>";
$page = include_once "templates/page.php";
echo $page;

The error I received is

Warning: Undefined variable $title

in C:\xampp\htdocs\ch2\templates\page.php on line 5

Warning: Undefined variable $content

in C:\xampp\htdocs\ch2\templates\page.php on line 9

I don't understand this as this is exactly what the book teaches, any help would be greatly appreciated and if there is a better way to use templates please remember I am a beginner so please Keep it simple!

P粉738346380P粉738346380219 days ago256

reply all(1)I'll reply

  • P粉129168206

    P粉1291682062024-02-18 13:04:26

    Your page.php looks a little strange. return is not what I use when printing html. Also, you are using php and html in the php tag, which won't work. Try this:

    
    
      
    <?php echo $pageData->title; ?>
    
    
    
    content; ?>
    
    

    You don’t need echo $page in your index.php, let page.php do it.

    /EDIT: There was also a typo on line 9: $pageData->$content; I've corrected it.

    reply
    0
  • Cancelreply