You can’t really have OOP without classes, so I thought I’d do a short intro to classes. In it’s basic form, a class can have properties and methods. They’re pretty much variables and functions, but the terms change when in the class context.
Here’s a basic class:
class car
{
var $model;
var $num_doors = 2;
public function __construct($model, $num_doors)
{
$this->model = $model;
$this->num_doors = $num_doors;
}
public function get_num_doors()
{
return $this->num_doors;
}
}
While this may look a bit daunting if you’re not used to classes, it’s pretty simple if you take it one bit at a time. First of all, notice that the syntax for making a class is just
class someClass
{
}
Properties are typically declared before the methods. You can also initiate the value of a property:
var $num_doors = 2;
One thing to remember is that you can’t do any expressions when initializing them. For example, this would be an error:
var $date = date('r'); // produces an error
A method can be made the same way normal functions are made in PHP. In classes, you can also specify the visibility of a function. Visibility can be any of the following:
- public – accessible from anywhere, even outside of the class
- protected – can be accessed from within the same class or a descendant class
- private – can only be accessed from within the same class
- final – can be accessed from anywhere but not overridden in a descendant class
$myCar = new car('F430', 2);
By doing that, I’m making an instance of the car class and giving it the name “myCar”. Two parameters are passed to the class, ‘F430′ and 2. Those parameters get passed to the constructor, __construct(). From there I can access methods using “$myCar->methodName()”:
echo $myCar->get_num_doors(); // echos 2 to the screen
“paamayim nekudotayim” is basically just two colons. The usage is as follows:
echo car::get_num_doors(); // echos 2 to the screen // pretty much... class::method();
Note that you can only do that if the visibility is either
- not set
- public
- or final
Trying to access a method with “::” from outside of it’s declared visibility will lead to an error.
Talking about why classes are so useful, inheritance, why visibility is useful, and best practices all merit their own entry in the future…