Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 property $poppy. Poppy, being a Dog, can bark by using the bark() method, and to do this, you need to use the special -> operator. Here is a complete script demonstrating creating objects—note that the method override for bark() is commented out.

    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() method in the Poodle class; running it again, you should see "Yip!" instead.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page