PHP Class and Object

PHP Class and Object


Classes and objects are the two main aspects of object-oriented programming.

Class: Class is a blueprint for any functional object, and it is defined by the programmer. It contains local methods as well as local variables. A class is defined in the program by using the class keyword, and followed by the name of the class and uses curly braces ({}).

For Example : Car is a class that having body parts (color,engine,Ac) perform many actions.

There are some rules for creating a class:

o The class name cannot include spaces.

o The class name should be started with a letter.

o The class name cannot be a reserved word of PHP.
 
Syntax :
       <?php
            class calculation{
             // statement to be executed
          }
          ?>
Below we declare a class named calculation consisting of three properties ($a, $b and $c) and two methods sum() and sub() .
 
 
Creating Class:

PHP - The $this Keyword :

The $this keyword refers to the current object, and is only available inside methods.

Object : Classes cannot do anything without objects. We have to define a class once and then can make multiple objects from a class, and it is created by using the new keyword. It is also known as an instance. Each object contains all the properties and methods which are defined at the time of creating the class, but they will contain different property values.

Example below :

Output : 25
               15