How do you use a class in PHP?

Using a class in PHP involves a few steps:

  1. Definition: First, you define a class with the class keyword, followed by the class name and a set of curly braces enclosing the class body.
   class MyClass {
       // Class properties and methods go here
  1. Including the Class (if it’s in another file): If the class is defined in another file, you need to include that file using require, require_once, include, or include_once. Alternatively, if you’re using an autoloader (like Composer’s), it will take care of including the necessary files as long as the namespace and directory structure are set up correctly.
  2. Importing the Namespace (if applicable): If the class is part of a namespace, and you’re in a different namespace or no namespace, you’ll need to import it with the use keyword (unless you want to refer to it with its full namespace every time).
   use Namespace\SubNamespace\MyClass;
  1. Instantiation: To use the class, you create an instance of the class (an object) by using the new keyword followed by the class name and parentheses.
   $myObject = new MyClass();
  1. Accessing Properties and Methods: After you have an instance of the class, you can access its properties and methods using the -> operator. Properties hold data, while methods are functions that belong to the class.
   $myObject->property = 'value'; // Set a property
   $myObject->myMethod();         // Call a method

Here’s a full example putting all these steps together:

// MyClass.php

namespace MyProject;

class MyClass {
    public $property;

    public function myMethod() {
        return 'Hello, world!';
// index.php

require_once 'MyClass.php'; // Include the class file
use MyProject\MyClass;       // Import the class from its namespace

$myObject = new MyClass();   // Instantiate the class
$myObject->property = 'Hi';  // Set a property
echo $myObject->myMethod();  // Output: Hello, world!

In a modern PHP project, you would typically skip the manual require step and rely on an autoloader, but the rest of the steps remain the same.