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

Properties

In the next code block, the line public $Name; defines a public property called $Name that all objects of class Dog will have. PHP allows you to specify how each property can be accessed, and we will be covering that in depth soon—for now, we will just be using public.

    class Dog {
            public $Name;

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

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 sign before Name. The following would be incorrect:

    $poppy->$Name = "Poppy";
    // danger!

While that will work, it won't access the Name property of $poppy. Instead, it will look for the $Name variable in the current scope, and use the contents of that variable as the name of the property to read from $poppy. That might be what you want, but otherwise, this will cause silent bugs in your code.

Each object has its own set of properties 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 properties are separate from Poppy's.

PHP allows you to dynamically declare new properties for objects. For example, saying "$poppy->YippingFrequency = 52820;" would create a new public property for $poppy called $YippingFrequency, and assign it the value 52820. It would create the property only for $poppy, and ...

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