Open In App

How to Define a Class in PHP?

To declare a class in PHP, we use the keyword class followed by the class name. Class names should follow the CamelCase convention and start with an uppercase letter.

Class Declaration:

class MyClass {
// Class properties, methods, and constructor go here
}

Properties:

Methods:

Constructor:

Example:

class Person {
public $name;
public $age;

public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}

public function greet() {
return "Hello, my name is {$this->name} and I am {$this->age} years old.";
}
}

Instantiating Objects:

$person1 = new Person("John", 30);
$person2 = new Person("Alice", 25);
Article Tags :