Object Orientation in PHP for beginners

I know many PHP programmers the concept of object-oriented programming scares them. I’ve been there. The syntax is different. But in this article I will try to understand object-oriented (OOP by its acronym in English), programming, programming style in which the actions are grouped into classes that help us to create more compact and easy to maintain code.

Object-oriented programming allows us to group similar tasks into classes . This helps us make sure we do not repeat code, which is one of the mantras of programming.

Perhaps you are wondering why it is important not to repeat code. The main reason is maintainability help it. Imagine you have “something” that is responsible for sending emails to people. For whatever reason, you have to add someone blind copy so they can see what emails are being sent. Can you imagine having that “something” spread to many places in the application and having to change it everywhere?  not cool .

Object-oriented programming is something that always intimidated at first, so let’s go slowly, holding hands .. Do not miss!

Objects and Classes

We started with something suavito. What is an object? What is a class? Are they the same? What is alike and different?

class is somewhat conceptual definition is rather the  basis of the objects . Classes define theproperties and  methods that can then use the objects. In terms of implementation, we use a user.We know that a user will have, for example, a value user and other security password as well as a  method for login .

The  object , on the other hand, is the user itself that fits what we have defined in the  class.therefore have the user juan password 01juan01 and we know you can do login . It is said that  john is an instance of the object User . We can have  hundreds  and hundreds  of users, but we know that they all have the same.

Now PHP

Create a class in PHP is quite simple and not much different to how it is done in other programming languages:

1
2
3
class User {
}

Now let’s see how we can create a john . Only have to avail ourselves of the keyword new .

1
$ John = new User;

By now easy, right?

Adding properties

A property is simply a variable, and use it to store information about the object itself. Let’s see how to add our properties.

1
2
3
4
class User {
    public $ user ;
    public $ password ;
}

Then see what is public . For now stick with the property is  public which means anyone can access it. After public, we have the name of the property.

Let’s see how to write and read these properties.

1
2
3
4
5
6
7
8
9
10
class User {    
    public $ user ;   
    public $ password ;
}
$ John = new User;
Harry $ -> user = 'john' ;
$ Juan -> password = '01juan01' ;
cast harry $ -> user; // juan

If you notice, we are using $ juan -> [Property_Name] . Perhaps you are wondering … why can not I do that? User-> user . The answer is, there may be any number of users and the value 01juan01 is inside the object, not the class.

Adding methods

Add method is as simple as adding properties. Let’s add a method to greet.

1
2
3
4
5
6
7
8
class User {
    public $ user ;
    public $ password ;
    public function hello () {
        miss 'Hello' . $ this -> user. '!' ;
    }
}

The first thing you’re wondering is … what is $ this ? $ this is the way they refer to objects themselves. Thus, to access the value of $ user from the object itself, we must avail ourselves of$ this .

Call the method does not have a lot of mystery:

1
2
3
$ John = new User;
Harry $ -> user = 'john' ;
Harry $ -> greet (); // Hi john!

Now, if we use multiple objects, we can store different values ​​in them and call its methods:

1
2
3
4
5
6
7
8
9
10
11
12
$ User = null;
$ Users [] = new User;
$ Users [] = new User;
$ Users [0] -> username = 'john' ;
$ Users [1] -> user = 'Manolo' ;
foreach ( $ users as $ user ) {
    $ User -> greet ();
}
// 'Hi john!'
// 'Manolo Hello!'

Magic Methods

PHP offers a number of magic methods that are called when we perform certain actions with the object, such as when an object is created. This helps us automate work at times.

Constructors and destructors

When a class is created or destroyed, it is called a magic methods as we advance. If we take action in either event, we have to define those methods and implement its functionality.

The method __construct () is called when we create a class and is usually a good place to fill in default information, or to form an object with something that comes from the database, etc.

1
2
3
4
5
6
7
8
9
10
11
class User {
    public $ user ;
    public $ password ;
    public function __construct () {
        $ This -> password = "1234" ; // Security to power!
    }
}
$ User = new User;
Echo $ user -> password; // 1234

Note that we can pass data to the constructor:

1
2
3
4
5
6
7
8
9
10
11
12
class User {
    public $ user ;
    public $ password ;
    public function __construct ( $ user ) {
        $ This -> password = "1234" ;
        $ This -> user = $ user ;
    }
}
$ User = new User ( 'john' );
Echo $ user -> user; // juan

Furthermore, when the destructor is called class is destroyed. This happens automatically when PHP finishes running, frees all resources associated have calling the method and will __destruct () of all classes in case you have. We can also force function using unset on the object. In the destructor are usually implemented closures connections to databases, freeing memory, etc.

Let’s look at a brief example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class User {
    public $ user ;
    public $ password ;  
    public function __construct ( $ user ) {
        $ This -> password = "1234" ;
        $ This -> user = $ user ;
    }
    public function __destruct () {
        Echo 'I die ...' ;
    }
}
$ User = new User ( 'john' );
unset ( $ user ); // 'I die ...';
There’s magic methods that have avoided because I do not consider important for a course basics of object orientation. But if you are curious or want to know more, not sure to take a look at the official documentation .

Class inheritance

This is where we will see one of the most powerful aspects of object orientation. A class can inheritproperties and methods from another class. This is useful when you want to add functionality to an existing class.

Following our example, our class father is User and now, let’s create a class daughter to beAdministrator .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class User {
    public $ user ;
    public $ password ;  
    public function hello () {
        miss 'Hello' . $ this -> user;
    }
}
class Admin extends User {
    public function banear ( $ user ) {
        Echo $ user -> user. "has been banned" ;
    }
}
$ User = new User;
$ User -> user = 'john' ;
$ Admin = new Manager;
$ Admin -> user = 'Super López' ;
Admin $ -> greet (); // Hello Super López
$ Admin -> ban ( $ username ); // juan has been banned

Using the keyword extends , the class Manager inherits the properties user and passwordand the method greet and have added a new method to ban this class by extending the basic functionality of a user. Perhaps the example is very absurd but please note that we may want to implement more complex functions such as login , logout , etc. and so we ended up saving lots of code.

What if I want to salute is different in Manager?

Overriding methods

Overriding a method is as simple as … re-define! In the child class, we redefine the method hello.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class User {
    public $ user ;
    public $ password ;  
    public function hello () {
        miss 'Hello' . $ this -> user;
    }
}
class Admin extends User {
    public function hello () {
        miss 'Hello admin >>' . $ this -> user;
    }
    public function banear ( $ user ) {
        Echo $ user -> user. "has been banned" ;
    }
}
$ Admin = new Manager;
$ Admin -> user = 'Super López' ;
Admin $ -> greet (); // Hello admin >> Super López

If you also want to keep the original functionality, we can do so by calling the function of the father :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class User {
    public $ user ;
    public $ password ;  
    public function hello () {
        miss 'Hello' . $ this -> user;
    }
}
class Admin extends User {
    public function hello () {    
        miss '' ;
        parent :: hello ();
        echo '!' ;
    }
    public function banear ( $ user ) {
        Echo $ user -> user. "has been banned" ;
    }
}
$ Admin = new Manager;
$ Admin -> user = 'Super López' ;
$ Admin -> greet (); // López Super Hi!

You see, we have mixed features of both methods.

Visibility of methods and properties

So far both properties and the methods we have seen, were all public . Now let’s see what that means and the other guys we have.

public

A methods and properties public , can be accessed from anywhere. Both within and outside the classroom.

protected

When you declare a property or method as protected , we can only access it from the class itself or its descendants (child classes).

private

The methods and properties private can only be read within the class itself that defines it . This brief example shows what would happen:

1
2
3
4
5
6
7
class User {
    public $ user ;
    private $ password ;
}
$ User = new User;
$ User -> password = 'Argofifa' ; // <- ERROR!

Classes and static methods

Classes and static methods can be any of the above types, public , protected or privatebut are unusual in not requiring the class is instantiated. In addition, the static properties keep the value during execution of the script. Let’s look at a brief example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class User {
    public $ user ;
    public $ password ;
    public static $ counter = 0;   
    public function __construct () {
        self :: $ counter ++;
    }
}
$ User1 = new User;
Echo User :: $ counter ; // 1
$ User1 = new User;
Echo User :: $ counter ; // 2

Note that when we refer to a static method or property, we can not use $ this , but we have access to self , which comes to the same thing just may use only static methods and properties.You can call methods and use properties from a public static method but not the other.

And here … for now. Right now I’d have to have a clearer idea of the style of programming with objects. I recommend that you start to try on your own and if you have doubts, come and currents.Learning object-oriented programming is one of the important steps in the life of every programmer.When carried out properly, the code produced will be easier to read, maintain and even can share classes between different applications as a class only should contain related class of its own code.

Sometime in the distant future I will publish an article on the MVC methodology, another major pitfalls that we encountered in our career programmers.

Do you think that something has been left to explain? Any point you do not understand? Already using object orientation and think you could give some advice to a beginner?

Courage! Leave a comment.

Leave a Comment

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

Scroll to Top