Class and Object in PHP

Rumman Ansari   Software Engineer   2020-02-02   5550 Share
☰ Table of Contents

Table of Content:


What is an object?

The fundamental idea behind an object-oriented language is to enclose a bundle of variables and functions into a single unit and keep both variables and functions safe from outside interference and misuse. Such a unit is called an object which acts on data. The mechanism that binds together data and functions is called encapsulation. This feature makes it easy to reuse code in various projects. The functions declared in an object provides the way to access the data. The functions of an object are called methods and all the methods of an object have access to variables called properties.

Class

In object-oriented programming, a class is a construct or prototype from which objects are created. A class defines constituent members which enable class instances to have state and behavior. Data field members enable a class object to maintain state and methods enable a class object's behavior. The following picture shows the components of a class.

Creating classes and Instantiation

  • The class definition starts with the keyword class followed by a class name, then followed by a set of curly braces ({}) which enclose constants, variables (called "properties"), and functions (called "methods") belonging to the class.
  • A valid class name (excluding the reserved words) starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
  • Class names usually begin with an uppercase letter to distinguish them from other identifiers.
  • An instance is an object that has been created from an existing class.
  • Creating an object from an existing class is called instantiating the object.
  • To create an object out of a class, the new keyword must be used.
  • Classes should be defined prior to instantiation.

Syntax



<?php
class Myclass
{      
 // Add property statements here
 // Add the methods here
} 
?>


In the following example keyword new is used to instantiate an object. Here $myobj represents an object of the class Myclass.

Syntax


<?php    
$myobj = new MyClass; 
?>


Let see the contents of the class Myclass using var_dump() function (display structured information (type and value) about one or more variables):

Syntax


<?php    
class Myclass
{      
 // Add property statements here
 // Add the methods here
}
$myobj = new MyClass;
var_dump($myobj);
?>


Output:


object(Myclass)#1 (0) { }