Okay, I've never delved into OOP with PHP before, but I've got a project right now that seems to present some opportunities to at least dip my toes in the water a bit a get a feel for it.
One such instance is a widget of sorts that will be used throughout the site. Basically, it's a listing of "related events" to present more info to the user.
It'll be re-used in several places, and depending on the usage, will need to show a certain number of items. So I figured I'd make a RelatedEvents class, pass the number items I want to feature into the class and let the magic begin.
Here's my existing (probably vomit-inducingly bad) code. I realize it's probably horrible, horrible practice to include some actual markup in the class itself as I've done - that's part of my question:
<?php
class RelatedEvents {
var $display_num;
var $rel_id;
function RelatedEvents($dnum,$rid){
$this->display_num = $dnum;
$this->rel_id = $rid;
# remember to use '$this->varname' when referring to variables in the class
?>
<div class="fixed-block">
<h2>Related Events <?=$testvar?></h2>
<div class="fixed-content">
<ul>
<li>
<p>info here...</p>
</li>
<li>
<p>info here...</p>
</li>
<li class="last">
<p>info here...</p>
</li>
</ul>
</div>
</div>
<?
}
}
?>
This works, on the very basic level of displaying the code on the page and being able to reference the variables in the constructor. However:
1) Am I a dumbass for including the markup in the Class itself? If that's bad news, what is the best practice for that - a class that basically serves to create markup.
2) Eventually, there will need to be a query associated with the class where the database is asked for x number of items (based on $display_num) relating to $rel_id. Can I include the query in the class itself? Currently, outside variables don't seem to work -- if I set $testvar outside of my class in the main PHP file, $testvar as shown in the class markup doesn't show display anything. So obviously I have to worry about the scope of things not a part of the class. So I'm assuming this will affect my ability to access my db connection and run a query in the class. How should I accomplish this?
3) Is this a stupid use of OOP? Am I better just doing something like:
$display_num = 2;
$rel_id = 5;
include "include_file_with_query_and_markup";
Any insight or guidance is greatly appreciated, since I have no idea what I'm doing.