PHP Class – OOP

A PHP Class can be used for several things, but at the most basic level, you’ll use classes to “organize and deal with like-minded data”. Here’s what I mean by “organizing like-minded data”. First, start with unorganized data.

<?php
$customer_name;
$item_name;
$item_price;
$customer_address;
$item_qty;
$item_total;
?>

Now to organize the data into PHP classes:

<?php
class Customer {
$name; // same as $customer_name
$address; // same as $customer_address
}

class Item {
$name; // same as $item_name
$price; // same as $item_price
$qty; // same as $item_qty
$total; // same as $item_total
}
?>

Now here’s what I mean by “dealing” with the data. Note: The data is already organized, so that in itself makes writing new functions extremely easy.

<?php
class Customer {
public $name, $address; // the data for this class…

// function to deal with user-input / validation
// function to build string for output
// function to write -> database
// function to read <- database // etc, etc } class Item { public $name, $price, $qty, $total; // the data for this class... // function to calculate total // function to format numbers // function to deal with user-input / validation // function to build string for output // function to write -> database
// function to read <- database // etc, etc } ?> Imagination that each function you write only calls the bits of data in that class. Some functions may access all the data, while other functions may only access one piece of data. If each function revolves around the data inside, then you have created a good class.