PHP Functions And Classes
Ranked #2,998 in Internet, #174,322 overall
What are functions and classes?
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.
function functionName( arguments ) {
task
}
Examples of built-in functions
Examples of built-in functions and usage of functions.
function pow($base, $exp) {
return($base^$exp);
}
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.
function displayWelcome( ) {
echo "Welcome to my website!";
}
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}!";
}
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
}
<?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);
}
?>
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");
Classes
The structure and usage of a class.
class className {
public properties variables
public function __construct( arguments ) {
class initialization
}
class functions
}
$object = new className( arguments );
DefinitionsBoth 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);
$object = new className(); //example object from example class
$object->variableName;
$object->functionName(arguments);
Creating Classes
Creating your own class and using it.
class Product {
public properties variables
public function __construct( arguments ) {
class initialization
}
}
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;
}
}
$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>";
<?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.
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!
}
}
<?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 ...
Next PHP Tutorial
Comments & Questions
Got any questions about the tutorial or just want to comment? This is the place to do so.
-
Reply
-
edzsquid
Aug 4, 2011 @ 4:31 am | delete
- thanks for the info!
-
Related Products (Amazon)
Related Products(eBay)
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 »
- 22 featured lenses
- Winner of 14 trophies!
- Top lens » PHP & MySQL Poll System Tutorial
Explore related pages
- PHP & MySQL Poll System Tutorial PHP & MySQL Poll System Tutorial
- PHP & MySQL Login System Tutorial PHP & MySQL Login System Tutorial
- PHP Smilies System Tutorial PHP Smilies System Tutorial
- PHP & MySQL Visitors Counter Tutorial PHP & MySQL Visitors Counter Tutorial
- PHP Banner Rotator Tutorial PHP Banner Rotator Tutorial
- PHP Email Validation Tutorial PHP Email Validation Tutorial