public, private, protected properties in PHP

Rumman Ansari   Software Engineer   2020-02-02   5412 Share
☰ Table of Contents

Table of Content:


Properties can be public, private or protected. Public means that properties can be accessed everywhere, private means properties can be accessed by the class that defines the member and protected means properties can be accessed only within the class itself and by inherited and parent classes.

Example:

Syntax



<?php
// Define a class
class Myclass
{
 // Declare $font_size as Public property
 public $font_size ="18px"; 
 // Declare $font_color as Private property
 private $font_color = "blue"; 
 // Declare $string_name as Protected property
 protected $string_name = "atnyla"; 
 // Declare a method to print properties value. This is public.
 function property_print()
 {
 echo $this->font_size;
 echo $this->font_color;
 echo $this->string_name;
 }
}
$obj = new MyClass;
echo $obj->font_size; //Display 18px 
echo $obj->font_color; //Fatal error: Cannot access private property Myclass::$font_color in F:\wamp\..
echo $obj->string_name; //Fatal error: Cannot access protected property Myclass::$string_name in F:\wamp\.. 
$obj->property_print(); //Display 18pxbluew3resource
?>