PHP Classes Tutorial


Lets start with our php tags

<?php
?>

create a page called index.php (or what ever)

<?php
// This is empty
?>

Create another page called class.php (or what ever)

<?php
class Demo {
function Animals(){
echo "Hello I am cat";
}
}
?>

So I have called the class “Demo”
and called a function “Animals”!
When a function is created in a class it is called a method
and it will echo “Hello I am a cat”;

Were done
Go back to index.php

<?php
include "class.php";
$Class = new Demo()
echo $Class -> Animals();
?>

This code will include “class.php”
and $Class = new Demo();
This means $Class = the class name (e.g. new Animals() )
we echo out Animals
$Class -> Animals(); or if we add anew function Cats we could put $Class-> Cats();

If you wanted to connect to a mysql database you could do this:

Connection.php

<?php
class Database 
{
var $Host;
var $Username;
var $Password;

function Connection()
{
$Connection = mysql_connect($this->Host, $this->Username, $this->Password) or die("Database Error");
}
}
?>

index.php

include "Connection.php"
$Database = new Database();

$Database->Host = "Localhost";
$Database->Username="root";
$Database->Password="";

$Database->Connection(); //Connect to database
?>
Advertisements

About ayumilove

I am Ayumilove, if you see some impersonators its not me.

One response to “PHP Classes Tutorial”

  1. manoj agarwal says :

    very gud script for starter classes of php .. G8 work.
    thanx dear

%d bloggers like this: