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 ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.