Private Access Modifier in PHP

In this article I will explain about private access modifier in PHP.
  • 1884

Introduction

It is quite clear, if you declare any variables or methods in PHP as private, then they can only be used inside the class. You cannot call the private method using the class object.

Example of Private access modifier

In the following example, the "title" property is set to be private, which means you cannot access it directly outside of this class by using its instance. Suppose you try to access $title for an instance $obj by using $obj->title; then it will generate an error. To solve this problem, here we define two public methods, the function "SetTitle()" sets the value in the "title property" and the function "DispTitle()" displays the "title" value.

<?php

class Myclass

{

private $title;

public function SetTitle($setval)

{

$this->title=$setval;

}

public function DispTitle()

{

echo $this -> title;

echo "<br />";

}

}

$obj = new Myclass();

$obj->SetTitle("ABCXYZ");

$obj->DispTitle();

?>

Output

Private-access-modifier-in-php.jpg

© 2019 DotNetHeaven. All rights reserved.