Basic PHP Class Tutorial

Creating and utilizing a PHP class is much easier than it looks or sound. If you start out with PHP a class might sound a bit confusing to you but it’s actually very basic. In layman’s terms see it as a bag of properties or even a database table with fields and you assign values to those fields or properties.

We will use a purchase order as an example.
Lets start out with our class in a php file like this.

class classPOHeader
{
	public $po_number;
	public $po_description;
	public $po_reference;
	public $po_date;
}

We can then assign a variable to the class.

$PO_HEAD = new classPOHeader(); 

And its all done! We are now able to give each property / field a value like this.

$PO_HEAD->po_number = 'PO00012456';
$PO_HEAD->po_description = 'Test PO';
$PO_HEAD->po_reference = 'Testref';
$PO_HEAD->po_date = '2018/11/29';

You can them echo them out on the page if you want to see the values that each property / field holds.

echo $PO_HEAD->po_number; //Echo out each field / property echo $PO_HEAD->po_description; //Echo out each field / property echo $PO_HEAD->po_reference; //Echo out each field / property echo $PO_HEAD->po_date; //Echo out each field / property

Below is all of the code combined.
myclasstest.php

<?php 
$PO_HEAD = new classPOHeader(); 
$PO_HEAD->po_number = 'PO00012456';
$PO_HEAD->po_description = 'Test PO';
$PO_HEAD->po_reference = 'Testref';
$PO_HEAD->po_date = '2018/11/29';

echo $PO_HEAD->po_number; //Echo out each field / property
echo $PO_HEAD->po_description; //Echo out each field / property
echo $PO_HEAD->po_reference;  //Echo out each field / property
echo $PO_HEAD->po_date; //Echo out each field / property


class classPOHeader
{
	public $po_number;
	public $po_description;
	public $po_reference;
	public $po_date;
}

?>

About the Author: Martin Viljoen

Leave a Reply

Your email address will not be published. Required fields are marked *