think of a method as just a regular php function but it happens to be inside a class, so they give it a fancy new name called Method
so here is a basic class structure
Code: Select all
<?php
class jimclass {
var $newname; // this is a variable that will be globally available to the entire class
function getName()
{
$name = htmlspecialchars($this->newname);
return $name;
}
function setName($name)
{
$this->newname = $name;
}
} // END OF CLASS
$user = new jimclass();
$user->setName('Jim');
echo 'Hi there, my name is '.$user->getName();
}
?>
now lets step through it and explain whats going on...
first line
class jimclass {
that is basically just giving my class a name and defining it as a class
that is what is called an attribute that is basically a defining characteristic of what the class is all about. for example if this class was to describe a human being.. a human's attributes might be hair color, eye color, height, weight.
Code: Select all
<?php
function getName()
{
$name = htmlspecialchars($this->newname);
return $name;
}
?>
what I'm doing here is returning the name variable with the html tags stripped out of it. maybe this class is used to validate user input so I want to return clean data. as you can see it looks just like a regular function in PHP but in a class its called a "METHOD". Think of it as a Method of getting data, setting data or manipulating data.
Code: Select all
<?php
function setName($name)
{
$this->newname = $name;
}
?>
thats whats called a setter method. basically you NEVER want to let anything outside the class touch your data. In PHP programmers can be lazy about this but its bad practice. The great part about OOP is that you can define who can touch your data. Basically you just want one entry point for setting your data for your class. It makes life alot easier when if something is wrong you can look in just one place.
Code: Select all
<?php
$user = new jimclass();
$user->setName('Jim');
echo 'Hi there, my name is '.$user->getName();
?>
so the first line I fire up my class and I'm assigning it the name $user so now $user is my object
next, I want to set my data(or set my name in this case). This could be a variable of anykind.
then I'm using the METHOD getName() to give me back my name. Notice the use of "->" thats basically saying "getName() is a method of my $user object so dont go looking for it as a function, go look in my class"
I hope that helps a little, its a simple example but getting the basics is key. The class works... so you can copy/paste and try it out.. then play around with it.
