PHP Tutorial: Classes and OOP
<?php
//PHP Tutorial: Classes and OOP
//The first thing you do is to define the class:
class cow
{
}
//Next, we'll create our first function - this is defined exactly the same as if you were not using classes:
// First we define the class
class cow
{
// Define the function moo() - no parameters
function moo()
{
// Define the variable
$sound = 'Moooooo';
return $sound;
}
}
//create the new class object 'in' a variable
// Create new cow object
$daisy = new cow;
//then call the moo() function
echo $daisy->moo();
//If you put this code together then, you will get something like this:
// First we define the class
class cow
{
// Define the function moo() - no parameters
function moo()
{
// Define the variable
$sound = 'Moooooo';
return $sound;
}
}
// Create new cow object
$daisy = new cow;
echo $daisy->moo();
//Ex. more functions
// First we define the class
class cow
{
var $eaten;
// Define the function moo() - no parameters
function moo()
{
// Define the variable
$sound = 'Moooooo<br />';
return $sound;
}
function eat_grass($colour)
{
if ($colour == 'green')
{
// cow is happy
$this->eaten = true;
return $this->moo();
}
}
function make_milk()
{
if ($this->eaten)
{
return 'Milk produced<br />';
}
else
{
return 'cow has not eaten yet<br />';
}
}
}
//call these functions and try out the new class
// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();
echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced
//final version
// First we define the class
class cow
{
var $eaten;
// Define the function moo() - no parameters
function moo()
{
// Define the variable
$sound = 'Moooooo<br />';
return $sound;
}
function eat_grass($colour)
{
if ($colour == 'green')
{
// cow is happy
$this->eaten = true;
return $this->moo();
}
}
function make_milk()
{
if ($this->eaten)
{
return 'Milk produced<br />';
}
else
{
return 'cow has not eaten yet<br />';
}
}
}
// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();
echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced
?>