PHP. Intro to OOP. Classes. Objects. Constructors

Home » Tutorials » PHP » 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:
keyword $this – its purpose is similar to javascript this. It calls to current object data.

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.

Code lesson


** Классы - имеют свои переменные (свойства, поля) и функции (методы)
** Конструктор - вызывается сразу после создания объекта

class Man {

    public $name;

    public function __construct($age) {
        echo "Вызов конструктора";
        $this->age = $age;

    public function getName() {
        return $this->name;

    public function setName($name) {
        $this->name = $name;
        return $this->name;


$kamil = new Man(27);
echo "<br>";

echo "<br>";

echo $kamil->getName();
echo "<br>";

echo $kamil->setName("Камиль");
echo "<br>";

echo $kamil->age;

$kamil->surname = "Абзалов";
echo "<br>";


Submit a Comment

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This