PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: Posting Code in the Forums to learn how to do it too.
Hello...
I'm learning PHP with the help of a book, but I can't full understand the operator $this-> (how it works):
<?php
class Cat
{
var $age;
function Cat($new_age)
{
$this->age = $new_age;
}
function Birthday()
{
$this->age++;
}
}
$fluffy=new Cat();
echo "Age is $fluffy->age <br/>";
echo "Birthday<br/>";
$fluffy->Birthday();
echo "Age is $fluffy->age <br/>";
?>
Can someone explain it to me or give me a link to a tutorial?
Thanks
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: Posting Code in the Forums to learn how to do it too.
class cat{
public $name;
function get_name()
{
return $this->name;
}
}
$cat1=new cat();
$cat2=new cat();
// here we have two instances of the class cat;
$cat1->name='Timmy';
$cat2->name='Jessie';
//now we've given them both names
print $cat1->get_name(); // this will print Timmy
print $cat2->get_name(); // this will print Jessie
if you need further help or a better explaination; don't hesitate to ask.
$cat1 is an instance of a class. It has it's own variables that belong to it, when you do $this->name='Timmy' you're giving the variable 'name' that belongs to cat1 a value of 'Timmy'.
you could have loads of variables that belong to a class such as.
class cat
{
public $age;
public $weight;
public $name;
public $breed;
function meow()
{
print "meow my name is ".$this->name." i am a ".$this->breed;
}
}
$cat1=new cat();
$cat1->weight=10;
$cat1->name="Timmy";
$cat1->breed="Tabby";
$cat2=new cat();
$cat2->name="Dave";
$cat1->breed="Black and White Cat";
$cat1->meow(); // this will say "meow my name is Timmy i am a Tabby";
$cat2->meow(); // this will say "meow my name is Dave i am a Black and White Cat";
so $cat1 and $cat2 are separate objects with their own variables and methods. Think of them as containers.
Google 'Object Oriented Programming' for more info. Or ask me if you need more help.
class cat
{
public $name;
function get_name()
{
return $this->name;
}
}
$cat1=new cat();
$cat1 -> name = 'Timmy'; // stored in member $name (public name)
If you want to change member outside class $object->member ($cat1 -> name). Inside class you must use special pseudo-variable $this-> ($this->name).
$cat2=new cat();
$cat2->name="Dave";
$cat1->breed="Black and White Cat";
$cat1->meow(); // this will say "meow my name is Timmy i am a Tabby";
$cat2->meow(); // this will say "meow my name is Dave i am a Black and White Cat";