OOP-Class and Object

Hello everyone, it’s Ray!

Today I’m going to share with you what class is, and what object is, also the relationship between them.

It’s hard to skip object when it comes to class, and vice versa, which is often what keep people from understanding.

Simply speaking, class is the code template that generates objects.

Talking is easy, let’s have some hand-on experiment first!

We could name a class with arbitrary name, which could be a combination of letters and numbers, and it must not begin with a number. Please take a look on the example below:

class MyAccessories
{
    // class body
}

The stuff above doesn’t look like a useful thing though, it’s a totally legal class.

As above mentioned, class is a template that generates objects. Now let’s create some objects as code below:

$accessory1 = MyAccessories();
$accessory2 = MyAccessories();

We use class “MyAccessories” to create two objects, and due to the same class that they come from, they share with the same functionality and type.

And you might ask, are they the same?

The answer is NO!

Although they are the same in functionality or type, they are indeed different objects

I know that you might still be confusing. Okay, let’s print them out. Add the following code:

var_dump($accessory1);
var_dump($accessory2);

I assume that you will print the stuff below, and you could see the number that follows pound sign, which represent their uniqueness. “Maybe the script shows the number in orders” You might say.

object(MyAccessories)#1 (0) {
}
object(MyAccessories)#2 (0) {
}

Okay, let’s have another experiment to make it crystal clear.

We switch the name of objects within var_dump braces, and if the script just shows the number in order, theorectically the number that follows pound sign will not change, will it?

var_dump($accessory2);
var_dump($accessory1);

I suppose that you will print something as follows:

object(MyAccessories)#2 (0) {
}
object(MyAccessories)#1 (0) {
}

See! The number after pound sign changed, which means the fact that even though they are generated with the same class, they have their own number that represent their uniqueness. That said each object is unique.

If you still have some confusion, let’s make an analogy as follows:

You could think of class as the a mould that produce a lot of castings, and objects are the castings that produced by the mould. They could be keycaps, or earphones. Despite the fact that they look identical on appearance, they are different. You might spot some serial number on them, and it’s like the number we printed earlier after pound sign.

Do you have more understanding on class and object after reading through this article?

Why git is so much required? Why should we use VIM?

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×