![]() |
![]() |
![]() | |
![]() International Sites:
|
Functions within ObjectsBut this still is not everything you can define in a class and do with an object. In our example and first object we accessed the object elements directly.
Through this we did not yet make sure that an alteration of the ZIP code entails an alteration of the city automatically. Normally a constructing programmer does not permit direct access from „outside“ onto elements in objects, but includes functions for this. That means that every access, no matter if reading or writing, onto object-internal variables should be handled with functions. Since these functions change object-internal data and therewith are in direct relation with these data, functions do logically belong to the object. Therefore functions are defined within the class. Let’s amend our address class with functions that, e. g., read out and write the name: Class Adress { var $Name; var $Street; var $ZIP; var $City; var $Country; function GetName () { return ($this->Name); } function WriteName ($NewName) { $this->Name = $NewName; // !!! Wrong: $Name = $NewName; } }
We defined two functions in this class. The syntax of the function’sdeclaration differs in no way from the normal declaration and we therefore do not attend to it further now. The only difference is that the functions have been defined within the class. Therewith the functions are not available global ! Another issue worth mentioning is access within functions onto elements of a class, i. e., onto class-internal „variables“. Hereto PHP provides a virtual object „$this“ which always refers to the current class. In order to access the „own“ elements of the class you have to do this in PHP via the object $this. In the example above we showed intentionally - in the line that is commentated off - how it is not done. $Name refers to a variable that would be valid only within the function and does not refer to the class element „name“ ! $MyAdress = new Adress; $MyAdress->WriteName ("Peter"); echo ($MyAdress->GetName ());
Class Adress { ..... function WriteLocation ($NewZIP, $NewCity) { $this->ZIP = $NewZIP; $this->City = $NewCity; } } You can revert to a function of the ancestor with the special name „parent“ followed by two colons. In this case we revert to the virtually overwritten function „WriteLocation“ of the ancestor and let it do the actual work. That saves a little bit of code - one line - and decreases redundance of code, which is indeed much more important ! [Back] - [Bookmark] - [Optimized for Printing] - [Send by E-mail] - [Contact] Copyright © 2000-2002 by Portunity GmbH (Germany) - All rights reserved. |
![]() ![]()
Direct links to the new Portalsuite 2002: |