You are currently viewing What is Visibility Mode in PHP | Types of Modes
  • Post category:PHP

What is Visibility Mode in PHP | Types of Modes

Visibility Mode in php

In this article, we will see what is php visibility mode. Normal variables can have scope “local – i.e can be accessed within its scope” and “global – i.e can be accessed anywhere in a program”. The variables used inside a function are invisible to the main program, and the scope is limited to local. PHP classes allow greater control over the visibility of object properties and methods. There are three levels of visibility available, public, protected, and private.

Property and method definitions are prefixed with the keywords public; this sets the corresponding class methods and properties to be “public” and allows a caller to manipulate them directly from the main body of the program. This “public” visibility is the default level of visibility for any class member (method or property) under PHP.

Protected methods and properties are visible to both their defining class (base class) and any child (derived) classes. Attempts to access these properties or methods outside their visible area typically produce a fatal error that stops script execution.

Ex:

<?php
//Base class
class Student{
public $rollno;
protected $age;
private $studname;
}

//Derived class
class Marks extends Student{
public $mark1;
public $mark2;
public $mark3;
}

$std1 = new Student;
$std1->rollno = '10'; // ok
$std1->age = 18; //fatal error
$std1->studname = "John"; //Error

$mark = new Marks;
$mark->rollno = '10'; // ok
$mark->age = 18; //fatal error
$mark->studname = "John"; //Error
?>

 

Leave a Reply