I’m attempting to create a php template that includes object oriented code. Here’s a simplified example of what I am trying to do.
index.php
<?php require 'requiredfile.php'; ?>
<html>
<body>
<h1><?php echo $object1->variable ?></h1>
</body>
</html>
But what if I wanted to use the same template for multiple objects? I definitely don’t want to have to create different versions of index.php for objects 1, 2 and 3. I’m assuming I could do something like $this->variable and pass in the object, but I’m not entirely sure how to do that since it’s outside the declaration of that class.
There is a nice trick to do what you want. Invert the logic and have the class call the template:
Now, inside the file
mytemplate.phpyou can call any property or method of the class by simply using$this->whatever.This pattern is easily reusable with different objects: