PHP - Declaring a Class

How to declare class?

class ClassName {

    // Properties (attributes)

    public $property1;

    protected $property2;

    private $property3;

    // Constructor (optional)

    public function __construct($arg1, $arg2) {

        // Constructor code

    }

    // Methods (functions)

    public function method1() {

        // Method code

    }

    protected function method2() {

        // Method code

    }

    private function method3() {

        // Method code

    }

}

Explanation of the parts:

class ClassName: This is where you define the name of your class.

Properties (attributes): These are variables that store data associated with the class.

public $property1: A public property that can be accessed from anywhere.

protected $property2: A protected property that can only be accessed within the class and its subclasses.

private $property3: A private property that can only be accessed within the class itself.

Constructor: The constructor method is automatically called when an object is created from the class. It's used to initialize the object's properties.

public function __construct($arg1, $arg2): A constructor method with optional arguments. You can perform initialization tasks within the constructor.

Methods (functions): These are functions that define the behavior of the class.

public function method1(): A public method that can be called from anywhere.

protected function method2(): A protected method that can only be accessed within the class and its subclasses.

private function method3(): A private method that can only be accessed within the class itself.

You can create an instance of the class using the new keyword:

$object = new ClassName();

You can then access properties and methods of the object using the arrow (->) operator:

$object->property1;

$object->method1();

Remember, this is a basic example. In real-world scenarios, classes can have more properties, methods, and complex behavior.