Starting OOP in PHP

PHP can be written in OOP (object oriented programming) style. This article will go over classes and objects in PHP.

Benefits of OOP

Using object oriented programming makes the code cleaner by providing a structure. This can be beneficial in the long run if the code is easier to maintain and repeated code is minimized.

Creating a class

Start by creating a class called Clothes. For the properties we have brand, which is the brand of the clothing and type is the type of clothing. Next, we create the setters and getters. Notice the $this keyword inside the methods, it refers to the current object.

<?php
class Clothes{
 public $brand;
 public $type; 

function set_brand($brand){
  $this->brand =$brand;
}
function get_brand(){
  return $this->brand;
}

function set_type($type){
  $this->type = $type; 
}

function get_type(){
  return $this->type;
}
}

Creating the objects

Now we start defining the objects in the class, to create a object we use the new keyword. $shirt is an instance of the class Clothes. For the end result, we print out the brand.

//objects
$shirt = new Clothes();
$shirt->set_brand('Gucci');
$shirt->set_type('Shirt');

echo "Brand: " . $shirt->get_brand();

Here is the full code for the example put together:

<?php
class Clothes{

 public $brand;
 public $type; 

function set_brand($brand){
  $this->brand =$brand;
}
function get_brand(){
  return $this->brand;
}

function set_type($type){
  $this->type = $type; 
}

function get_type(){
  return $this->type;
}
}

//objects
$shirt = new Clothes();
$shirt->set_brand('Gucci');
$shirt->set_type('Shirt');

echo "Brand: " . $shirt->get_brand();
?>

PHP beginner resources

Here are my 2 favorite resources for learning PHP:
W3 schools
Hacking with PHP

24