Access Modifiers

Access modifiers are used to control access to members of a class (properties and methods). The access modifiers in PHP are:

  1. public
  2. private
  3. protected

The default access modifier in PHP is public. When we set the access modifier as private for a property or method and try to access it from outside the parent class, we will encounter a fatal error.

Let us create a program to get and set values for a class as below:

<?php

class Car {

    private $model;

    public function getModel()
    {
        return "The model is " . $this->model;
    }

    public function setModel($model) 
    {
        $this->model = $model;
    }
}

$mercedes = new Car();
$mercedes->setModel("Mercedes");
echo $mercedes->getModel();

results matching ""

    No results matching ""