How to use PHP templates correctly
P粉738346380
P粉738346380 2024-02-17 19:44:27
0
1
299

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粉738346380
P粉738346380

reply all(1)
P粉129168206

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!