PHP Objects

PHP OOP object is the instance of the class. Objects can be created from the class through a new keyword. We can create more than one object from the class. The process of creating objects from the class is known as instantiation.

Object Characteristics

  • The Object is created from the class.
  • You can create more than one object from a class.
  • During the creation of an object new keyword is used.
  • Class properties and methods can be accessed by these objects.
  • To access class properties and methods, use this -> operator.

How To Create Object

General Syntax

      $object = new ClassName;
$object = new ClassName();
    
Try it now

Source Code

          <?php  
class House{ 
  public $houseColor;
  public $houseModel = "ASD202"; //property
  public function geetMessage(){ //method
	  echo"This house model is really best.";
  }
}

$myHouseObject = new House;
//creating object
$myFriendHouseObject = new House;  
//creating object
?>
        
Try it now

Here, two objects namely $myHouseObject and $myFriendHouseObject are created using the class House.

How to access class property & method?

Class property and method can be accessed by -> operator.

General Syntax

      $obj->classPropertyName;
$obj->classMethodName();
    
Try it now

Source Code

          <?php  
class House{ 
 public $houseColor;
 public $houseModel = "ASD202"; //property
 public function geetMessage(){ //method
  echo"This house model is really best.";
 }
}
$myHouseObject = new House;//creating object
$myFriendHouseObject = new House;  //creating object
$myHouseObject->houseModel;
$myHouseObject->geetMessage();
?>
        
Try it now

Please keep in mind that, do not put $ sing before the property and method name during accessing the property and method of an object.

Web Tutorials

PHP Objects
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4