Table of Contents

    Properties in PHP Classes: Defining Data Fields

    Properties in PHP Classes: Defining Data Fields
    • 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

    
    
    <?php   
    class Myclass
    {
     public $font_size =10;
    }
    $f = new MyClass;
    echo $f->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

    
    
    <?php
    class Dress{  
    	public $color = "red";  // The color of the dress 
    	Public $fabric = "linen"; // The fabric of the dress 
    	Public $design = "Slim Fit Blazer";//The design of the dress   
    
    }
    
    $dressObj = new Dress();
    $dressObj->color = "Black";
    
    var_dump($dressObj); 
    echo "</br></br>";
    print_r($dressObj); 
    ?>