Class is a user defined data type. It is a template or blueprint, which holds data members (properties) and member functions(methods). To use these members of a class, its Objects are created.

To implement OOPS in PHP, class and its object is used.

How to define class

class is a keyword followed by a class name and a pair of curly braces ({}) used to define a class in PHP. Inside curly braces properties and member functions are placed.

Syntax

class classname{
 // data members or properties
 // member function or methods
}

Class naming rules

  1. It must not be a reserved word.
  2. A class name can start with underscore or letter followed by any character or number.
  3. Should not start with any number.
  4. Should not contain space.

Example

class Mobile{
 
// Properties
  public $company;

  // Methods
  function set_name($company) {
    $this->company = $company;
  }
  function get_name() {
    return $this->$company;
  }

}

Objects

To use class, object needs to be created. With object class Data members and member function can be accessed.

How to create class object

new keyword is used to create class objects, Any number of class objects can be created.

Syntax

classname object = new classname();

Example

class Mobile{
 
// Properties
  public $company;

  // Methods
  function set_name($company) {
    $this->company = $company;
  }
  function get_name() {
    return $this->$company;
  }

}
// Object Created below
Mobile myPhone = new Mobile();

Accessing class members

Example

class Mobile{
 
// Properties
  public $company;

  // Methods
  function set_name($company) {
    $this->company = $company;
  }
  function get_name() {
    return $this->$company;
  }

}

Mobile myPhone = new Mobile();
myPhone->set_name("Motorola");
myPhone->get_name();

$this keyword PHP

$this is a keyword, refers to current object of a class. $this is accessible inside class only, using outside will give an error. using $this, allows to access class properties inside its methods.