PHP Class in depth analysis (Part 1)

Before jumping to the PHP Class, let’s observe our surroundings for a moment. You see tangible things in your room like books, table, chair, clothes etc. Each of these items may or may not be useful to you.

Let say you have a book. But you don’t have just one book, maybe you have few or many. But books nevertheless. If you ask school going kid what he has in his bag, he will most probably answer “books”.

In our world, there are millions and millions of books. Some are thick, some are thin. Some are big and heavy, some are light and pocket sized. But they are still books. Hope you agree to this point.

Now, lets examine a book. What are things you see?

You will see the book title, the author, the ISBN code, published date, number of pages, the table of contents, the actual content and more. These are the most common properties that you will see in most books.

Whether the book is on philosophy, science or cooking recipes, you will see most of these mentioned properties. Though properties are same, their values are different.

For e.g the books Oliver Twist and A Tale of Two Cities are written by the same author Charles Dickens. These two books are written by the same author, but their titles, ISBN and content are completely different.

They fall under classic literature category. But still, different books  because they are uniquely identified by their ISBN or title.

PHP class declaration

So, I know, that the book titled Oliver Twist was authored by Charles Dickens and is classified a literature novel with number of pages etc. You know that the “Book” is parent category and all these properties mentioned fall under its domain.

Let’s codify our example. Open your text editor and save it as index.php on your localhost installation.

Declaring PHP Class

This is the basic PHP class declaration. Lets add the properties we mentioned

Declaring PHP Class with properties

Now, I have a class called “Book” and properties such as $book_author, $isbn etc all belong to it. If you understood up to this part, then create some classes on your own. For e.g Automobile, Humans, Foods, anything that you see around yourself. List their common properties and declare a class for these properties. Don’t worry about the public keyword for now.

Continue to Part 2

Recommended resource: Class basics PHP.net

Leave a Comment

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