9.4 Making Variables or Functions Public and Private


9.4 Making Variables or Functions Public and Private

You want to make certain variables or functions inaccessible to the person accessing your class.

Technique

There is no way of declaring functions and variables private to a class without putting them within the scope of a function. However, as a standard naming convention, you should always start private methods and variables with an underscore ( _ ):

 <?php class Car {     var $_name; // private     var $brandname;     function analyze() {         if ($this->_name == "Corolla") {             $this->brandname = 'Toyota';         } else {             $this->_delete();         }     }     function _delete() {         $this->name = '';         $this->brandname = '';     } } ?> 

Comments

In languages such as C++ and Java, you can set certain variables accessible to only the methods of the same class. However, PHP does not offer this functionality. Therefore, you must trust that users of the class will make use of only public variables and functions. One way of labeling a variable or function as private to most programmers is by putting an _ before the variable or function name. This is also a good reminder of what is public and what is private if you have to work on your class in a couple of months and you don't remember much about it.

Another thing to keep in mind about scope and class data is that variables declared within a class are not global. They are part of a class and therefore accessible only via an object created from that class. To be global, a variable must be outside of the class definition. The same also holds true with constants: As a rule, you should define your constants outside the scope of the class in order to access them within the class.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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