Properties in PHP Classes: Defining Data Fields
☰Fullscreen
Table of Content:
- Class member variables are called properties. Sometimes they are referred as attributes or fields.
- The properties hold specific data and related with the class in which it has been defined.
- Declaring a property in a class is an easy task, use one of the keyword public, protected, or private followed by a normal variable declaration. If declared using var (compatibility with PHP 4), the property will be defined as public.
- public : The property can be accessed from outside the class, either by the script or from another class
- private : No access is granted from outside the class, either by the script or from another class.
- protected : No access is granted from outside the class except a class that’s a child of the class with the protected property or method.
Example:
After an object is instantiated, you can access the property of a class using the object and -> operator. Any member declared with keyword "private" or "protected" cannot be accessed outside the method of the class.
Syntax
font_size; ?>
Output
10
Note: There is a common mistake to use more than one dollar sign when accessing variables. In the above example there will be no $ sign before font_size (echo $f->font_size).
Another Example
Syntax
color = "Black"; var_dump($dressObj); echo ""; print_r($dressObj); ?>