Objects

Classes are mere definitions - you cannot play fetch with the definition of a dog, you need a real, live, slobbering dog. Naturally we cannot create live animals in our PHP scripts, but we can do the next best thing - creating an instance of our class.

In our earlier example, "Poppy" was a dog of type "poodle". We can create Poppy by using the following syntax:

$poppy = new poodle;

That creates an instance of the class poodle, and places it into the variable $poppy. Poppy, being a dog, can bark by using the bark() function, and to do this you need to use the special -> dereference marker. Here is a complete script demonstrating creating objects - note that the function override for bark() is commented out.

<?php
    class dog {
        public function bark() {
            print "Woof!\n";
        }
    }

    class poodle extends dog {
        /* public function bark() {
            print "Yip!\n";
        } */
    }

    $poppy = new poodle;
    $poppy->bark();
?>

Execute that script, and you should get "Woof!". Now try taking out the comments around the bark() function in the poodle class, and running it again you should see "Yip!" instead.

 

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: Variables >>

Previous chapter: Overriding functions

Jump to:

 

Home: Table of Contents

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