PHP: istanziare una classe con i dati presi dal database

PHP: istanziare una classe con i dati presi dal database

In PHP è semplice istanziare una classe con i dati presi dal database.

La nostra implementazione:


class Product {
    protected $id;
    protected $price;
    protected $name;

    public function __construct($id) {
        $this->id = $id;
        $this->price = 0.00;
        $this->name = '';
        $this->getData();
    }

    public function getPrice() {
        return $this->price;
    }

    public function getID() {
        return $this->id;
    }

    public function getName() {
        return $this->name;
    }

    private function getData() {
        $result = $db->getResult("SELECT price, name FROM products WHERE id = " . $this->id);
        $this->price = $result->price;
        $this->name = $result->name;
    }
}

Esempio d'uso:


$product = new Product(100);
echo $product->getPrice(); // 92.00

Torna su