A class in PHP

A software program instruction is having or involving several parts, elements, or members of codes. Program code written to solve specific problems. Think of a book having multiple chapters describing a story. Each chapter can be seen as a class in programming, way of thinking. 

Class’s are a blueprint of real life object’s. When we have a Dog class, it will have a dog property and behavior. A dog will never become a cat but they are both animal. You may ask yourself right now how to make a dog bark? First you have to create a kind of dog you want to make bark and next you have to create an event which triggers the bark method from the dog object.


 <?php class Dog { } ?> 


Reserved keyword ‘class’ and the name of the class, “Dog”. The name of the class could be anything that you want to picture. A class could be named by a single vocabulary or multiple words therefor concerning readability use CamelCase as a solution. The opening and closing curly brackets are the body of the class. It is a place to add related methods and properties into the class.

Variables or fields

Variables are like vocabularies. They have their meanings inside their value and type. A software object’s state is stored inside a variable.


 <?php class Dog { public $name = “DogName”; } ?>

A variable named ‘name’ with a ‘public’ visibility which makes it visible and accessible by all the members inside the Dog-object. Declaring a variable, this step involves stating the variable type and its descriptive name.

Methods or functions

A single page in a book could be seen as a method or function. A software object’s behaviour is shown via its methods.

<?php class NewClass { public $name = “YourName”; function setName( ) { $this->name = “newName”; } function getName() { return $this->name; } }?> 

The NewClass object has two methods, functions or behaviours in the design seen above. The getName(); method gets the value from a variable or container from its container NewClass. The method setName(); sets a value.


A class become an object only, when it is instantiated. <?php $obj = new Newclass(); echo $obj->getName(); ?>

Defining the new NewClass class in another class is called instantiating. 

We have seen datatypes like String, Integer and so on but those are called predefined datatypes. We also have user defined datatypes. 

Since instantiating the NewClass object in another class called NewClassObject, we have now created our own datatype named NewClass.