PHP abstract class (my first impressions)
I’ve been using PHP for a while now, but I’ve never dug too deep into it’s programming strengths. I’ve recently been thrown into using abstract classes in PHP. This article is just a first impression of what they are, and how I see them being useful in a project.
First, what is an abstract class? In not-so-technical terms, they seem to be just like a normal class. You define methods, variables, use a construct function, and can declare items as private or public.
abstract class FormBuilder {
public $method;
public $action;
public $name;
function __construct($name,$action,$method) {
$this->name = $name;
$this->action = $action;
$this->method = $method;
}
}
However, you cannot create instances of these class’s directly. You must create another non-abstract class and extend the abstract class.
class LoginForm extends FormBuilder {
function printForm() {
print '<form name="'.$this->name.'" method="'.$this->method.'" action="'.$this->action.'">';
print '... form body ...';
print "</form>";
return true;
}
}
$frontPageLoginForm = new LoginForm();
$frontPageLoginForm->printForm();
In this case you could move to creating a info request form, submit story form, or any kind you may need. Then create instances of those class’s as needed with methods and attributes custom taylored to the data that class handles.
So, why write the abstract class? In this case we could create a lot of form types, and build up the parent class to handle validation, creating form fields and storing variables that are relative to all forms (e.g. a unique id generator or timestamp.)
Then build up the classes that extend the abstract class to define less used and not-so-global features. In this case maybe username and password, along with a password encryption method may only make sense to a login form, not a request info form.
I think this starts to make a lot more sense as you start to use them more. At first, I thought ‘why not just build them into the main class?’ But as our team started extending those class’s more and more, it became obvious why we used that structure when we were able to tweak one validate method in the parent abstract class to fix a glitch in error handling was one file rather than multiple files.
Check out the PHP Manual for a much more technical view of PHP abstract classes.