{PHP} Intro into Classes
Requirements
A WebServer
PHP 4.1.x or higher
So you want to be a php developer or you are already a php developer seeking to learn the missing link. If you have programmed or scripted with any languages such as c++ or asp, youll find they use classses and/or objects in the coding standards.
This option isnt default for php but still an option. Classes are good for alot of things, and it is used for many big projects such as Invision Power Board, this method is known as Object Oriented Programming.
Part I : Writing your first class.
In this example we will be building an extension of the basic echo function. Save this file as echo_class.php
PHP Code:
<?php
class xechos {
################################
#we have the class started now for its contents
###############################
function xechos() {
echo "This is an echo function with a bit of a oop twist";
}
################################
#well thats it, our function.
################################
}
################################
#end the class.
################################
?>
Code Explanation.
PHP CODE:
<?php
Well duh, this starts our php document
PHP Code:
class xechos{
This starts off the class for xechos
PHP Code:
function xecho() {
echo "This is an echo function with a bit of a oop twist";
}
this is the php function xechos, which uses the echo function to bring This is an echo function with a bit of a oop twist.
And thats it you have made your first class.
Part II : Using functions in your class
Youve probably thinking, ok moron, you taught me how to make a class and not to use it, which is why I wrote this section.
add the following to echo_class.php
PHP Code:
<?php
$xechos = new xechos;
$xechos->xecho();
?>
Code Explanation
PHP Code:
$xechos = new xechos;
This declares your class as a var so you can use functions stored in a class. The first parameter is the var name, this doesnt matter as long as its not declared anywhere else, the second would be declaration, which you put new classname, classname being replaced with your actual class of course.
PHP Code:
$xechos->xecho();
This is how you use a function in a class, this bit of code must be used after you declare your class as a var, then you put the var name you decalred you class as, in this example is $xechos, then ->, then the function you want to use.
Your script should have printed out, This is an echo function with a bit of a oop twist, if not then re-read this tutorial cuz you did something wrong
Last edited by Nitro; 28-02-2007 at 10:40.
|