i

PHP Tutorial

PHP-Classes/Objects

In Object oriented programming, a class is considered to be a template for the objects and object is known as the instance of a class. For example, if Car is a class then Audi, BMW, Mercedes are the objects of this class. The car has its own attributes like name, speed, mileage etc. and all the cars will have these attributes.

So, when we create a class, we define some attributes that will be common to the objects of this class. When an object is created, all the objects will have some value for all the attributes of their class.

You can define a class using class keyword and give the name of the class and mention all the properties and methods inside curly braces {}.

Syntax: class class_name { //properties and methods }

We can create methods for setting the properties and getting the properties as below:

class Car {

public $name; //properties

public $color;

function set_name($name) {  //method

$this -> name = $name; }

function get_name($name) {

return $this -> name; }

}

?>

$this keyword refers to the current object of a class and is only used inside the methods of class.

Classes need objects as they would not have any meaning otherwise. You can create multiple objects from a class, and it will have all the properties and methods of the class but a different value for those properties. You can create an object using new keyword.

class Cars {
  public $name;
  public $color;

  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
  function set_color($color) {
    $this->color = $color;
  }
  function get_color() {
    return $this->color;
  }
}

$Audi = new Cars();
$Audi->set_name('Audi');
$Audi->set_color('Black');
echo "Name: " . $Audi->get_name();
echo "
";
echo "Color: " . $Audi->get_color();
?>

You can also change the property of an object outside the class by using below PHP code:

class Cars {
  public $color;
}
$BMW = new Cars();
$BMW->color = "White";
?>