When And Why We Should Use OOP in PHP?

Imagine you are working in PHP for few months or you have won a project or you are establishing yourself for a future in PHP. You have written all the code in past in public scope without classes or objects.

Believe me nobody will ask you to write a code in PHP using classes. It is a luxury and quite handy one but it is entirely your decision to use it. That makes PHP such a brilliant language. It is as effective as any other OOP based language and works great. But lets say code in greater than 1000 lines and its very normal. You will be lost in code in minutes. You risk writing same code again and again and this leads to more and more errors eventually.

So you should start using classes and objects now after facing some real time problems not on your boss’s request or client’s will. By the way, clients will never say that. They do not care. They want a code which works. It is up to you to make it work for longer period of time and according to changing business requirements of clients.

Now question is why we should use OOP? What it will give to your code?

Modularity. Yes it will break your code in different modules. It will add complexity at start but eventually your code will be readable for you and other developers in your team. For example, lets talk about a website for products. So product will be a class. It is very simple.

class Product {
	
}

Just like that you have created your first class. Simple? Now you will place all variables and function related to product in your Product class. For example,

class Product {
	public  $name;
	public  $price;
	public  $description;

	public function addProductInDatabase(){
		//save product in database
	}

	public function findProductByName() {
		//find and return product information
	}

	public function changePrice() {
		//find and return product information
	}
}

Now every noun in your class will be its attribute. Name, Price or Description etc. and every verb will be a function, addProductInDatabase, findProductByName, changePrice. Simple! Now what is Object? Suppose you have no product in your store yet but you want to plan for every possibility. You will start with a blue print so that you are ready for first product when it will arrive. That blueprint is class and your actually product will be an object. This does not mean you will have to write as many objects as products in your store but object is something which is using your class finally for good purpose. It is very easy to make objects of your class.

$product = new Product();
$product->name = "Purel";
$product->price = 100;
$product->description = "it is used to sanitize hands.";

$product->addProductInDatabase();
$product->changePrice();
$product->findProductByName();