Section 8.4. Properties


8.4. 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 soonfor 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 not for any other instances of the same class.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net