Access Modifiers – PHP OOP

Access Modifiers in PHP

Access modifiers can be put on properties and methods to control how and where they can be used.

There are three things that change access:

  • public: public means that anyone can use the property or method.
  • protected: This is protected by default, so the property or method can be used within the class and by classes that are based on it.
  • private: private means that the property or method can only be accessed within the class.

In the next example, we’ve given three properties three different access modifiers (name, color, and weight). If you try to change the name property here, it will work (because the name property is public, and can be accessed from everywhere). But if you try to set the color or weight property, you will get a fatal error (because the color and weight properties are protected and private):

Example

<?php
class Student {
public $name;
protected $rollno;
private $dob;
}

$ram = new Student();
$ram->name = ‘Ram’; // OK
$ram->rollno = ‘100’; // ERROR
$ram->dob = ’30/10/1990′; // ERROR
?>

In the next example, we have given two functions access modifiers. Even though all of the properties are public, if you try to call the set color() or set weight() functions, you will get a fatal error. This is because the set color() and set weight() functions are private and protected:

Example

<?php
class Student {
public $name;
public $rollno;
public $dob;

function set_name($n) { // a public function (default)
$this->name = $n;
}
protected function set_rollno($n) { // a protected function
$this->rollno = $n;
}
private function set_dob($n) { // a private function
$this->dob = $n;
}
}

$ram = new Student();
$ram->set_name(‘Ram’); // OK
$ram->set_rollno(‘100′); // ERROR
$ram->set_dob(’30/10/1990’); // ERROR
?>

People also search

Leave a Comment

Scroll to Top