DEV Community

Cover image for Starting OOP in PHP
Coding Fatale
Coding Fatale

Posted on

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;
}
}

Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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();
?>
Enter fullscreen mode Exit fullscreen mode

PHP beginner resources

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

Top comments (1)

Collapse
 
arvindpdmn profile image
Info Comment hidden by post author - thread only accessible via permalink
Arvind Padmanabhan

Perhaps you already know the basics of OOP. If not, read this devopedia.org/object-oriented-prog...

Some comments have been hidden by the post's author - find out more