PHP Access Modifiers
Access modifiers are used to control where properties and methods can be accessed.
There are three access modifiers :
public
- From anywhere, a property or method can be accessed. As a result, this setting is the default.protected
- Within the class and by classes descended from it, the property or method can be accessed.private
- Only members of the class have access to the property or method.
Example 1 :- A simple program for different access modifier.
name = 'Billgates'; // OK
$p1->gender = 'Male'; // ERROR
$p1->age = 55; // ERROR
?>
Try setting the name property and it will work (because the name property is public). But if you try to set the "gender" or "age" property, a fatal error will appear (because the gender and age property are protected and private) :
Related Links
Example 2 :- Adding two public methods to access the private and protected properties.
gender = $gender;
}
public setAge($age)
{
$this->age = $age;
}
}
$p1 = new Person();
$p1->name = 'Billgates';
$p1->setGender("Male");
$p1->setAge(55);
?>
Now, There will be a question on your mind? Why we have create public methods to access private members?
The answer is "To collect proper input data".
Example 3 :- Adding two public methods to access the private and protected properties.
= 18 && $age2 <= 60)
{
$this->age2 = $age2;
}
}
function getAge2()
{
return $this->age2;
}
}
$p1 = new Person();
$p1->age1=10000;
echo "Age 1 = " . $p1->age1 . "
";
$p1->setAge2(130); // It will not set
echo "Age 2 = " . $p1->getAge2() . "
";
$p1->setAge2(30);
echo "Age 2 = " . $p1->getAge2() . "
";
?>
Age 2 =
Age 2 = 30
The age1 property has invalid data because of direct access. But you cannot provide any invalid data on age2 property.
Note: You have a option to control your input data by using private modifier.
Related Links