PHP Classes (original) (raw)
Last Updated : 19 Apr, 2025
A class defines the structure of an object. It contains properties (variables) and methods (functions). These properties and methods define the behavior and characteristics of an object created from the class.
**Syntax:
**Now, let us understand with the help of the example:
PHP `
`
Output
The class "GeeksforGeeks" was initiated!
**In this example:
- The code defines a Car class with two properties: color and model.
- The __construct method initializes the properties when a new Car object is created.
- The displayDetails method prints the car’s model and color.
- A new Car object is created using new Car(“Red”, “Toyota”), passing values for color and model.
- The displayDetails method is called on the $myCar object to display the car’s details.
**Creating Objects from Classes
Once a class is defined, you can create objects based on it. Here’s how you can create an object from a class:
$object = new ClassName('Hello', 'World');
echo $object->method1(); // Outputs: Hello World
**In this example:
- new ClassName() creates an instance (object) of the class ClassName.
- The constructor is called with the parameters ‘Hello’ and ‘World’, which are passed to initialize the object’s properties.
- The method method1 is called on the object to display the concatenated properties.
Best practices for using the PHP classes
- **Use Meaningful Names: Give classes, methods, and properties descriptive names that clearly indicate their purpose. This makes your code easier to understand and maintain.
- **Encapsulate Data: Use private or protected properties and provide public getter and setter methods to access or modify them. This keeps the data safe and controlled.
- **Keep Methods Short and Focused: Methods should do one thing and do it well. Avoid long, complex methods. This makes your code more understandable and easier to test.
Conclusion
PHP classes are the foundation of Object-Oriented Programming. They allow you to model real-world entities, encapsulate data, and define behaviors that can be reused across your application. By using properties, methods, constructors, and taking advantage of inheritance and polymorphism, you can create robust and scalable PHP applications.