PHP. Intro to OOP. Classes. Objects. Constructors
Today we’ll begin series of tuts about OOP (object oriented programming). First of all we’ll talk about OOP basics – classes, objects and constructors.
Why do you need to use OOP in your projects? Thee say, OOP is difficult for understanding. But it’s not true. OOP lets you to create very flexible code, which you may reuse. If you make a goof architecture of your app, you can ver easy switch off some modules in your app, and your app will be work fine.
Today we’ll create class and object of this class. Class is template of real essence. This is another advantage of OOP – to look data as a real essence. There are a lot of essences in our world – men, cars, houses and so on. This is how we will think about data in OOP principles.
As you understand, man is scalar and complex data type simultaneously. If you would write app to count men, men was a scalar data. But now we must understand and consider men as a complex data type, which can communicate with other essences. Every essence has its own key properties. For example, men have got first name, last name, age and so on. In classes it’s called class properties. Also men can do some actions – to walk, to breathe. In classes it’s called methods. See class code example below.
A few more remarks on the class:
What is object? Objects are real men. Class is “template” of men. Accordingly, every object is unique, but at the same time every object has its own properties and methods, which are inherent in absolutely all people.
At last let’s talk about constructor. Constructor is a method, which called automatically, after object creation (string 28 in code). It’s purpose is initial setting of object (seting of properties and etc). In real projects in constructors you may to init connection with database for example.