PHP Product Class with Getter and Setter Methods
This Snippet is coded by a user inOnline php Compiler. You can see and run this code too.
زبان: PHP
This code defines a simple Product class in PHP, demonstrating object-oriented programming (OOP) principles such as encapsulation and data hiding. The class has two private properties: $name and $price.
Public getter methods (get_name() and get_price()) allow reading the values, while setter methods (set_name() and set_price()) allow updating them. This ensures controlled access to the object's data.
After creating an instance of the class, the code sets the name to 'bag' and the price to 1000, then outputs a string displaying the product details.
Usage:
- Instantiate the class with
$product = new Product(); - Set values using setter methods.
- Retrieve values using getter methods.
This pattern is widely used in PHP applications for maintaining clean and maintainable code.