PHP class with comparable interface
Write a class called 'Product' with properties like 'name' and 'price'. Implement the 'Comparable' interface to compare products based on their prices.
Sample Solution:
PHP Code :
Sample Output:
Desktop is more expensive than Laptop
Explanation:
In the above exercise -
- The Comparable interface declares a single method compareTo() that accepts another object for comparison.
- The "Product" class implements the Comparable interface and defines the compareTo() method.
- The Product class has two private properties: $name and $price, representing the product's name and price.
- The constructor method __construct() is used to initialize the values of the properties when creating a new instance of the Product class.
- The getName() and getPrice() methods retrieve name and price, respectively.
- The compareTo() method compares two Product objects based on their prices. It returns -1, 0, or 1 indicating whether the current object is less than, equal to, or greater than the compared object.
Flowchart:


PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: PHP class inheritance with extended class.
Next: PHP class with a static property.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics