PHP Classes and Objects


In this tutorial, we will learn about PHP Classes and Objects. As we know Object-oriented programming is a programming paradigm, based on the concept of classes and objects. In very easy language a class is the blueprint of the object and an object is a run time instance of that class. Let's check how to define a class and create an object in PHP.

Defining a class:

In PHP, the class keyword is used to define a class. We write the class keyword followed by the class name and after that, we define the properties and methods of the class in curly braces {}. Please check out the following example program to understand this.

<?php
class Student {
  // proerties and methods will come here...
}
?>

In the above example program, you can see how we have created a Student class.

For good coding practice always write class name starting from captial letter.  For e.g. Student, Person, Car etc.

We can define properties and methods in the class. Please check out the following program.

<?php
class Student{
  // Properties
  public $name;
  public $age;

  // Methods
  function set_properties($name, $age) {
    $this->name = $name;
    $this->age = $age;
  }

  function get_properties() {
    echo $this->name.' '.$this->age;
  }
}
?>

Creating an Object in PHP:

An object is a run time instance of the class. We can create multiple objects of any class and each object will have all the properties and methods defined in the class. Each object will occupy a different space in memory and each object have the ability to set different values for properties.

In PHP we use the new keyword to create objects of the class.

Please check out the following example program to understand the concept of objects wisely.

<?php
class Student{
  // Properties
  public $name;
  public $age;
 
  // Methods
  function set_properties($name, $age) {
    $this->name = $name;
    $this->age = $age;
  }
 
  function get_properties() {
    echo $this->name.' '.$this->age;
  }
}

//creating objects using new keyword
$student1= new Fruit();
$student2 = new Fruit();

//calling to set properties method of Student class
$student1->set_properties('Rahul',19);
$student2->set_properties('Mohit',20);

//calling to get properties method of Student class
echo $student1->get_properties();
echo "<br>";
echo $student2->get_properties();
?>

 



Spread the love:

Please share this page on social media with your friends..

Facebook share Twitter Linkedin share