PHP oops - What is Object?

An Object is an instance of class. PHP Object is used to access properties and methods of class.

A variables are called properties and functions are called methods in class. We can call member methods of class using object.

We can create multiple objects from a class. Each object will have different property values.

We can create new object using "new" operator as per as below.

PHP Syntax:

Object variable name = new keyword class name;

<?php

class  Class_name{

        function getMethod()
        {
             //code to be executed!
        }

  $obj= new Class_name;

}

?>

new keyword  is used to allocate memory for object.

PHP Example :

<?php
class Game{
    
    public $name;
    
    function set_game($name)
    {
        $this->name=$name;
    }
    
    function get_game()
    {
         return $this->name;
         
    }
    
   
    
}

 $cricket = new Game();
 $hockey = new Game();
 $football = new Game();
 $cricket->set_game("Cricket");
 $hockey->set_game("Hockey");
 $football->set_game("Football");
 echo "</br>I would like to play ".$cricket->get_game();
 echo "</br>I would like to play ".$hockey->get_game();
 echo "</br>I would like to play ".$football->get_game();
 
?>

Output:

I would like to play Cricket
I would like to play Hockey
I would like to play Football

Comments

Leave a Reply

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

41674