Search⌘ K
AI Features

Solution Review: Access Modifiers

Explore how to implement and manage PHP access modifiers in object-oriented programming. Understand using private properties with public getter and setter methods, and test these concepts by building a User class that securely handles data access.

We'll cover the following...

Solution

PHP
<?php
class User {
private $firstName;
public function setFirstName($str){
$this -> firstName = $str;
}
public function getFirstName(){
return $this -> firstName;
}
}
function test()
{
$user1 = new User();
$user1 -> setFirstName("Joe");
return $user1 -> getFirstName();
}
echo test();
?>

Explanation

  • Line 2: We write the User class with the $firstName private property.
  • Line 5: We add the public setter method
...