HOME HTML EDITOR C JAVA PHP

PHP Classes and Objects

Classes and objects are the two main aspects of object-oriented programming. A class is a template for objects, and an object is an instance of a class.

1. Defining a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces {}. Inside the braces, we define Properties (variables) and Methods (functions).

<?php
class Car {
  // Properties
  public $brand;
  public $color;

  // Methods
  function set_brand($brand) {
    $this->brand = $brand;
  }
  function get_brand() {
    return $this->brand;
  }
}
?>

2. Creating Objects (Instantiating)

To create an object from a class, we use the new keyword. You can create multiple objects from a single class; each object will have its own set of property values.

<?php
$toyota = new Car();
$ford = new Car();

$toyota->set_brand("Toyota");
$ford->set_brand("Ford");

echo $toyota->get_brand(); // Outputs: Toyota
echo $ford->get_brand(); // Outputs: Ford
?>

3. The $this Keyword

The $this keyword refers to the current object. It is only available inside methods. It tells PHP to look for the variable belonging to the specific object that called the method.

<?php
function set_brand($brand) {
  $this->brand = $brand; // "this" brand belongs to this specific object instance
}
?>

4. The instanceof Keyword

You can use the instanceof keyword to check if a specific object belongs to a specific class. This is very useful for validation in complex applications.

<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit); // Returns: bool(true)
?>

5. Modifying Properties Directly

While we use methods (getters and setters) for better control, you can also access and change public properties directly using the -> operator.

<?php
$toyota = new Car();
$toyota->brand = "Toyota Corolla";
echo $toyota->brand;
?>
Important: Always use PascalCase for Class names (e.g., MyClassName) and camelCase for methods and properties (e.g., myMethodName). This is the standard coding practice in PHP.