PHP Classes and Objects

1. Class: A class shares common behaviors and characteristics of a real world object. Such as a car class shares it's characteristics like color, engine, wheels, model and behaviors such as drive, reverse, stop etc. In programming languages a class contains it's own variables and functions. PHP is an object-oriented scripting language. For creating a class, you should use the class keyword, followed by the class name, followed by an opening brace and a closing brace. All the variables and methods of the class you should write between the opening and closing braces. Class variables are called as properties and methods are called functions. The syntax of class is mentioned below: Syntax: Code


<?php class className{ }
?>
The example of class is mentioned below:
Code

// first example
<?php
  class Book
  { 
    $title; 
    $numPages; 
  }
?>

// second example
<?php
  class Book
  { 
    $title;
    $numPages; 
    
    function setNumPages($numOfPages)
    { 
      $numPages = $numOfPages; 
    } 

    function getNumPages()
    { 
      return $numPages; 
    }
     
    function setTitle($Title)
    { 
      $title = $Title; 
    } 

    function getTitle()
    { 
      return $title; 
    } 
  }
?>

// Third example
<?php 
  class myFirstClass 
  { 
    public $firstVariable = "First Member Variable";

    function firstFunction() 
    { 
      print "Inside 'firstFunction()'"; 
    } 
  } 
?> 

Object

An instance of a class called object. An object has it's own characteristics and functions. Such as a car object have characteristics like it's red color, four wheels etc. The example of object creation is mentioned below:

Code

<?php
  $firstObject = new myFirstClass; 
  echo $firstObject->$firstVariable;
  echo $firstObject->firstFunction();
?>
We have created an object of 'myFirstClass' class which is mentioned in above example. You can access member variables and functions of a class as same as mentioned in the above mentioned example.