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:
- Define class properties (variables) inside the class using visibility keywords (
public
,protected
, orprivate
). - Properties store object data and represent the state of the object.
Methods:
- Declare class methods (functions) inside the class to define its behavior.
- Methods perform actions or provide functionality related to the class.
Constructor:
- Optionally, define a constructor method
__construct()
to initialize class properties when an object is created. - Constructors are automatically called upon object instantiation.
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:
- To use a class, instantiate objects from it using the
new
keyword followed by the class name and optional constructor arguments. - Objects are instances of a class and hold their own set of properties and methods.
$person1 = new Person("John", 30);
$person2 = new Person("Alice", 25);
Contact Us