PHP Functions And Classes

Ranked #2,998 in Internet, #174,322 overall

What are functions and classes?

In this tutorial functions and classes will be explained, but first off: what actually are functions and classes and what are they used for?

Functions
Functions consist of variables and commands ( use of other functions inside of the function ). Each function is made to complete its own certain task. When you're building a large system you'll need a lot of tasks inside of the system to be done. Therefore it can be very useful to let each task have its own function for it. This way the code becomes a lot more clear and also more efficient. You wouldn't want to have to rewrite the code for a certain task for each case that it's used for. Why not just write one function that can complete the task for any case as long as you provide the certain case to the function? Using functions in your code is the first step to making your code more efficient and useful to other programmers.

Classes
When you program using classes & objects ( instances of classes ) you're into Object Oriented Programming. This is even a step further into making your codes more efficient and clear. When you have a lot of tasks that your system is capable of doing, and you made them each into seperate functions, there may still be a lot of different kinds of functions. For example functions that take care of the system or more specificly of user accounts, or functions that take care of the user interface (the look of your webpage), etc.. But they aren't connected in any way. With classes this can be done: a class in fact is the structure of an object and consists of methods(functions) to alter the object and variables that define the object. This way all functions that belong together can be put inside one class and function together for the sake of a certain object/process.

Pre-Knowledge
It's recommended that, before you start on this tutorial, you already mastered the PHP basics.

Functions

The structure and usage of a function.

The structure of a function ( how it's formed ) is like this:

function functionName( arguments ) {
task
}

The prefix function is put before the name of the function to indicate that we're creating a new function with the following name ( in this case functionName ). After the name of the functions we put the arguments of the function between brackets: these are the variables that the function needs values for in order to do its task. The actual task the function completes with the use of the arguments provided, is put between accolades.

Examples of built-in functions

Examples of built-in functions and usage of functions.

There are a lot of functions in PHP that are already built-in. An example of such function we have seen in the php basics tutorial. Which was the PHP built-in function echo($str), which requires one arguments to be given in order to function: a string (text) to display. However this function is pretty abstract as we cannot easily imagine how the function does this. An easier example would be the built-in function pow($base, $exp), which raises the base to the exponent provided and returns that result. The arguments of this function are $base and $exp - which are the variables that are required to be given a value to in order for the function to work. We could actually rewrite/reconstruct this function as that's pretty easy in this case. The function probably looks similiar to this:

function pow($base, $exp) {
return($base^$exp);
}

Note: this is not the exact code the pow function is based on. It's just a model to illustrate the functionality of it.

The arguments required for the function are put between brackets and the return value ( what is returned when the function is called ) is a simple output of a calculation $base^$exp.

We can call the function by simply typing the function name followed by the values for the arguments of the function between brackets. In this case the function returns a number, so we would want to catch it inside of a variable for example.

$result = pow(2, 4); //which returns 2^4 = 16 and stores this inside the variable $result

we could also directly display the return of the function by putting it as argument to another function: the echo function.

echo( pow(2,4) ); //pass a function return as argument for another function

which immediately displays 16 on the screen.

Creating Functions

Creating your own functions and using them.

Now it's time to actual create our own function, to get a better understanding of how it all works. We'll first create a very simple function that displays a welcome message on the screen.

function displayWelcome( ) {
echo "Welcome to my website!";
}

And if we call it:

displayWelcome();

it would display the text "Welcome to my website!" on the screen. Now we didn't use any arguments for this function, as it always does the same: displaying the very same message on the screen. Which is pretty useless; we could've just made a variable for this and echo it when necessary. So, let's make it a bit more 'useful' by adding an argument which is used to display a welcome message for a certain user:

function displayWelcome($username) {
echo "Welcome back, {$username}!";
}

And if we call it like this:

displayWelcome("Bill Gates");

it would display the text "Welcome back, Bill Gates!" on the screen. We can make it display a welcome message for any user this way, which is already a bit more useful.

Now let's make a larger function. We'll create a function that can convert bytes2kilobytes, bytes2megabytes, kilobytes2megabytes, otherways around, etc.. We'll need a few arguments for our function to complete it's task: it needs to know the original value, the size type (bytes/kilobytes/megabytes/etc.) and the size type it needs to be converted into.

function convertSize($size, $type1, $type2) {
convert $size from size type $type1 into size type $type2
}

Now we need to write the code to convert $size from filesize type $type1 (for ex. bytes) into filesize type $type2 (for ex. kilobytes). We'll need to distinguish a certain amount of cases: first we need to distinguish the cases from all filesize types (values $type1 may have and $type2 may have). To do this we'll use a switch loop.

<?php
function convertSize($size, $type1, $type2) {
for($i=1;$i<=2;$i++) {
$type = "type{$i}";
$factor = "factor{$i}";
switch($$type) {
case "bytes":
$$factor = 1;
break;
case "kilobytes":
$$factor = 1024;
break;
case "megabytes":
$$factor = pow(1024,2);
break;
case "gigabytes":
$$factor = pow(1024, 3);
break;
case "terabytes":
$$factor = pow(1024, 4);
break;
}
}
$size_final = ($factor1/$factor2)*$size;
return (round($size_final,2)." ".$type2);
}
?>

Note: $$variablename refers to the variable with as name the value of $variablename. E.g. when $variablename = 'test1' then $$variablename = $test1.

We go through the switch loop for both $type1 (the original filesize format) and $type2 (the desired filesize format). Instead of rewriting the same code to do it for both, we put it in a small for-loop that runs twice ( once for $type1 and once for $type2 ). Then for both filesize formats (types) we define a relative factor where bytes is factor 1, kilobytes factor 1024 ( as 1*1024 bytes = 1 kilobyte ), megabytes 1024*1024 ( as 1*1024*1024 bytes = 1 megabyte ), etc.. This way we can define the factor to go from format $type1 (e.g. bytes) to format $type2 (e.g. kilobytes) by defining the multiplying factor to $factor1(=relative factor of format $type1)/$factor2(=relative factor of format $type2). For example: the original filesize format ($type1) is bytes -> $factor1 = 1, the desired filesize format ($type2 is kilobytes -> $factor2 = 1024 -> $factor = 1/1024, which is correct: each byte is 1/1024th of a Kilobyte! It may be a little bit complex to understand but I hope it's become pretty clear ( otherwise feel free to ask your question at the bottom of this page ("Comments & Questions") ).

Now we can use our function to convert any filesize from any format to any format by just calling it. For example:

//displays the amount of kilobytes equal to 2048 bytes (=2 kilobytes)
echo convertSize(2048, "bytes", "kilobytes");

And we already created our own neat filesize convertion function which can be pretty useful at the same time!

Classes

The structure and usage of a class.

The structure of a class is basicly to be seen like this:

class className {

public properties variables

public function __construct( arguments ) {
class initialization
}

class functions

}

As you can see from the above structure a class is formed out of functions and properties (variables that define the class). The construct function is a built-in function which is used to initialize the class. When an object (instance) of the class is created, this __construct function is automaticly executed for the instance of the class. There can be set arguments for this function as well. These need to be given when creating an object of the class, which can be done this way:

$object = new className( arguments );

Definitions
Both variables and functions can be defined in 3 ways: public, protected or private. Here are the differences between these 3 types of variables/functions:

public
Variables and functions from this type are visible and useable from anywhere: inside and outside of the class.

protected
Variables and functions from this type are visible and useable from within the class or parent class (extended class).

private
Variables and functions from this type are visible and useable only from within the class in which they're made.

Using class properties and functions
To use properties and functions of the class within the class itself, $this can be used. For example:

$this->variableName;
$this->functionName(arguments);

From outside of the class, when an instance is made of the class (object), it can be done by using the variable that contains the instance of the class (object):

$object = new className(); //example object from example class
$object->variableName;
$object->functionName(arguments);

Creating Classes

Creating your own class and using it.

Now let's create some simple example class. We'll create a class that defines a product. We'll call the class, simply, Product.

class Product {

public properties variables

public function __construct( arguments ) {
class initialization
}

}

Now we need to think of the properties that define a product. These need to be given as arguments to the construct function when an instance of the product class (a product object) is created. We'll also define them inside of the class as properties of the class:

class Product {

//class properties
public $name;
public $description;
public $price;
public $type;

public function __construct( $name, $details, $price, $type) {
//initialize the class by setting the properties equal to the values that were given to the arguments of the construct function
$this->name = $name;
$this->details = $details;
$this->price = $price;
$this->type = $type;
}

}

Now we've set up the basics for the product class. When we want to make a product object (instance of the class) we'll now need to supply the name, details, price and type of the product in order to create object. The construct function sets the properties of the class equal to those that were given to the construct function. For example:

$product1 = new Product("Samsung Galaxy S II", "A great mobile phone with a powerful processor.", "599.95", "Mobile Phone");

And we can test whether the properties for the product were correctly assigned to the object:

echo "<p><b>Product:</b> ".$product1->name."</p>";
echo "<p><b>Type:</b> ".$product1->type."</p>";
echo "<p><b>Details:</b> ".$product1->details."</p>";
echo "<p><b>Price:</b> $".$product1->price."</p>";

Which should output the properties of the product we just created. We could also make this into a simple function of the class. So we'd only have to call that certain function to display all info about the product.

<?php
class Product {

//class properties
public $name;
public $description;
public $price;
public $type;

public function __construct( $name, $details, $price, $type) {
//initialize the class by setting the properties equal to the values that were given to the arguments of the construct function
$this->name = $name;
$this->details = $details;
$this->price = $price;
$this->type = $address;
}

public function display( ) {

//displays the product info
echo "<p><b>Product:</b> ".$product1->name."</p>";
echo "<p><b>Type:</b> ".$product1->type."</p>";
echo "<p><b>Details:</b> ".$product1->details."</p>";
echo "<p><b>Price:</b> $".$product1->price."</p>";

}

}

//create the product object
$product1 = new Product("Samsung Galaxy S II", "A great mobile phone with a powerful processor.", "599.95", "Mobile Phone");

//display the product info
$product1->display();
?>

Extending Classes

Extending a class.

It's also possible to extend classes. This basicly means you create a new class based on an existing one. The new class that extends the class its based upon, may use any (public and private) variables and functions from the parent class. For example:

class BasicClass {
public $welcome_message = "Hi there, welcome to my website!";

public function __construct( ) { }

public function sayHi() {
echo $this->welcome_message;
}
}

class NewClass extends BasicClass {
public function __construct( ) {
$this->sayHi(); //outputs: Hi there, welcome to my website!
}
}

An example of the actual usage of extending classes could be for example to have a main class called system and a lot of other classes, such as for handling user accounts, templates, etc., which make use of the system class ( extend it ) as the system class contains all main functions that are used in other classes to. Here's another example to illustrate the use of extending classes:

<?php
//a product class that applies for all products in general
class product {
//the main properties of a product in general
public $name;
public $description;
public $price;

public function __construct( $name, $description, $price ) {
$this->name = $name;
$this->description = $description;
$this->price = $price;
}

public function buy($amt) {
echo "Bought product '".$this->name."' (x{$amt})";
}

}

//a product-specific classes, that apply for certain types of products
class television extends product {
public $size;
public $display_quality;

public function __construct( $name, $description, $price, $size, $display_quality ) {
$this->name = $name;
$this->description = $description;
$this->price = $price;
$this->size = $size;
$this->display_quality = $display_quality;
}
}

$tv1 = new Television("Samsung LE32C450 - 32" LCD-TV", "Some random Samsung television.", "254,- EU", "32 inch", "HD-Ready");
$tv2 = new Television("Samsung LE37C530 - 37" LCD-TV", "Another random Samsung television.", "418,- EU", "", "Full-HD");
echo "<p>TV1 is ".$tv1->name." and is ".$tv1->display_quality." </p>";
echo "<p>TV2 is ".$tv2->name." and is ".$tv2->display_quality." </p>";
echo "<p> <b> ".$tv1->buy()." </b> </p>";
?>

You might also like ...

Loading

Next PHP Tutorial

Loading poll. Please Wait...

Comments & Questions

Got any questions about the tutorial or just want to comment? This is the place to do so.

submit

Related Products (Amazon)

Loading

Related Products(eBay)

Loading

by

webcodez

"Give a man a program and you'll frustrate him for one day. Teach a man to program and you'll frustrate him for a whole lifetime."

webcodez
GameHeroes
more »

Feeling creative? Create a Lens!