I’ve been making a webpage with php and html following this tutorial. I was trying to setup a template where I could set various variables like title of the page, content, etc. But I’ve been running into some trouble getting things to set properly.
In my index page I have php start like:
<!DOCTYPE html>
<?php
include('includes/meta.php');
$md = new metadata();
$md->setTitle("HELLOOOO");
?>
...<!-- rest of html -->
then in my Metadata class in meta.php (contains the HTML):
<?php
class metadata
{
private $title = "default";
public function setTitle($title) { $this->title = $title; }
public function getTitle() { return $this->title; }
}
?>
<head>
<meta charset="utf-8">
<title>
<?php $md = new metadata();
echo $md->getTitle();?>
</title>
But “default” is always echoed for the title.
How can I properly set variables in separate classes / files? And what is the best convention of accomplishing this?
You’d need a singleton, because when you do
new metadata();, you’re creating a new object, when in fact you want the one to reference the one that was created first.Here is a sample implementation:
Now, you need to do:
To get an object of the metadata class.
See it work