Variables

You've seen that it is quite easy to define functions for your classes, and it is just as easy to define variables. Take a look at this new class definition for our dog class:

class dog {
    public $Name;

    public function bark() {
        print "Woof!\n";
    }
}

The line public $Name; is the key - it defines a public variable called $Name that all objects of class dog will have. PHP allows you to specify how each variable can be accessed, and we will be covering that in depth soon - for now, we will just be using "public".

Author's Note: when designing your own classes, consider putting an underscore in front of object variables so as to distinguish them from parameters passed into an object's functions and also local variables. This is not done here for the sake of maximum readability, plus of course I don't want people who missed this note to think using an underscore is required!

We can now set Poppy's name by using this code:

$poppy->Name = "Poppy";

Notice that -> is used again to work with the object $poppy, and also that there is no dollar before Name. The following would be incorrect:

$poppy->$Name = "Poppy";

PHP's variables have one dollar sign and one only. The reason for this is because the incorrect line of code works like a variable variable - PHP would look up the value of $Name, then try to set that value inside $poppy. The following code would work, but is kind of crazy:

$poppy= new poodle; $foo = "Name"; $poppy->$foo = "Poppy";
print $poppy->Name;

Author's Note: Just in case you were skimming over this section and missed out on the warning, PHP's variables have one dollar sign and one only. If you have more, eg $$foo or $foo->$bar, it means something entirely different and is generally left to the realm of advanced programmers.

As mentioned already, each object has its own set of variables that are independent of other objects of the same type. Consider the following code:

$poppy = new poodle; $penny = new poodle; $poppy->Name = "Poppy"; $penny->Name = "Penny";
print $poppy->Name;

That will still output "Poppy", because Penny's variables are separate from Poppy's - hopefully you can now see quite how well OOP models real world scenarios!

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: The 'this' variable >>

Previous chapter: Objects

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.