Skip navigation.
Allow sufficient time for real learning

Chapter 15 Hints and Help

QUESTION: What is the difference between class variables, attributes, and fields?

ANSWER: These are all different names for variables that are used interchangably to describe variables that are declared at the class level (rather than inside methods). The name field comes from database terminology (and class variables are often associated with database fields), while the name attribute is part of standard OO terminology.

QUESTION: The textbook states that class variables are usually private or protected but can also be public. How would an application access a public class variable?

ANSWER: Class variable can be declared as private (only visible to methods in the same class), protected (visible to methods of the same class and any child classes), and public (visible to any application that creates instances of the class). If a class variable is public it can be accessed by instances of the class, similar to the way that public methods are accessed. For example a public method named getAge(), can be called by an instance named myAge as follows: myAge->getAge(), and a public method named setage() could be used to set the age to 40 as follows: myAge->setAge(40). If a class variable named $age was public it could be accessed directly without need for these methods, using myAge->age. So you could then set the value directly using $myAge->age= 40;. Usually it is considered poor design to allow applications direct access to the data in an object; instead the class variables (data) are usually protected by making them private, accessible only by public methods. This practice ensures that the processes used to access and modify the data are controlled by the object. We say the private data is encapsulated by the public methods.