Simple OOP exercises in PHP

Do you want to master object-oriented programming?

Yeah? Here I leave you exercises with a solution for this purpose.

Careful! You will find the solution after executing the exercise.

Content

  • Class creation exercise
    • track 1
    • track 2
    • Solution
  • Method creation exercise
    • Solution

Class creation exercise

In this OOP exercise I ask you to:

create a PHP class that allows managing the products of an online store. Each product will have to have: title, reference or SKU, unique identifier, price with taxes, price without taxes, tax percentage and units in stock.

You have 15 minutes to create the file and the structure of the class, as well as its corresponding methods.

track 1

The file name should be Product.php or Product.class.php.

track 2

Class attributes should be private or private.

private $titulo;
private $referencia;
private $id;
private $precio_sin_impuestos;
private $precio_con_impuestos;
private $porcentaje_impuestos;
private $stock;

Solution

<?php
//fichero Producto.class.php

class Producto {
	private titulo;
	private referencia;
	private id;
	private precio_sin_impuestos;
	private precio_con_impuestos;
	private porcentaje_impuestos;
	private stock;

	public function __construct($titulo, $referencia, $id, $precio_sin_impuestos, $precio_con_impuestos, $porcentaje_impuestos, $stock){
		$this->titulo = $titulo;
                $this->referencia = $referencia;
		$this->id = $id;
		$this->precio_sin_impuestos = $precio_sin_impuestos;
		$this->precio_con_impuestos = $precio_con_impuestos;
		$this->porcentaje_impuestos = $porcentaje_impuestos;
		$this->stock = $stock;
	}
	
	public function get_titulo(){
		return $this->titulo;
	}
	public function set_titulo($new_titulo){
		$this->titulo = $new_titulo;
	}

	//repetir getters y setters por atributo de la clase;


}

Method creation exercise

Now, about the previous class, I want you to manage the price correctly.

You will have to modify the method setter of the tax rate. We need that when changing the percentage the price with taxes is recalculated.

Note: the final price of a product is price_without_taxes multiplied by tax_percentage divide by 100 and add 1. That is: price_without_taxes * (1 + percentage_taxes / 100);

100 * ( 1 + 21 / 100 ) => €121

Solution

<?php
	public function set_porcentaje_impuestos( $porcentaje ) {
		$this->porcentaje_impuestos = $porcentaje;
		$this->precio_con_impuestos = $this->precio_sin_impuestos * ( 1 + $porcentaje / 100);
	}
?>

Leave a Reply