How to correctly use PHP templating

79 Views Asked by At

I am new to PHP and I'm currently working through 'PHP for absolute beginners' book. In the book it is currently teaching about templating and using the StdClass() Object to avoid naming conflicts.

I have a file for templating called page.php and a file for my homepage called 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 errors i am receiving are

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 it is exactly what the book is teaching any help would be appreciated and please if there are any better ways to use templating please remember I am a beginner so keep it simple!

1

There are 1 best solutions below

1
Chrostip Schaejn On

Your page.php looks a little odd. return is not something I would use in context of printing html. Also, you are using php and html within the php tag which can't work. Try this:

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

You don't need echo $page in your index.php, let the page.php do that.

/Edit: There is also a typo in line 9: $pageData->$content; I corrected that.