Properties
In the next code block, the line public $Name; defines a public property called $Name that all objects of class A 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 A {
public $Name;
public function say( ) {
print "Hello!\n";
}
We can now set B name by using this code:
$p->Name = "ABC";
Notice that -> is used again to work with the object $p, and also that there is no dollar sign before Name. The following would be incorrect:
$p->$Name = "ABC";
// DANGER!
While that will work, it won't access the Name property of $p. 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 $p. 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:
$p = new B;
$pq = new B;
$p->Name = "ABC";
$pq>Name = "XYZ";
print $p->Name;
That will still output "ABC", because XYZ properties are separate from ABC.
PHP allows you to dynamically declare new properties for objects. For example, saying "$p->YappFrequency = 12345;" would create a new public property for $p called $YappFrequency, and assign it the value 12345. It would create the property only for $p, and not for any other instances of the same class.
0 comments:
Post a Comment