Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to avoide exposing the public properites

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 84
    Comment on it

    In this tutorial we will see the how to avoid exposing the public properites of any class in oop as it is always a good practice to use encapsulation while coding.One of the main advantage of hide the public properties is that if we want to make some change in a code it can be done in isolation and that will have no effect on other area of the code. The best way for hiding the public properties is to put all the fields as private and expose these fields with the help of public accessors.Below is the example of how to use public accessors:


    Example:

    //This is the example of code where we directly access the public properties
    
    class Employee
    {
        public $firstName;
        public $lastName;
        public $city;
    }
    
    $emply = new Employee();
    $emply->firstName = "Peter"; 
    $emply->lastName = "Goomes";
    $emply->city = "xyz";
    echo "FirstName:"; echo($emply->firstName);echo "<br>";
    echo "LastName:";  echo($emply->lastName);echo "<br>";
    echo "City:";      echo($emply->city);
    
    OUTPUT:
    
    FirstName:Peter
    LastName:Goomes
    City:xyz
    

    Below is the example where we use accessors for accessing the private properties

    class Employee
    {
        private $firstName;
        private $lastName;
        private $city;
    
        public function setFirstName($firstname)
        {
            $this->firstName = $firstname;
        }
    
        public function getFirstName()
        {
            return $this->firstName;
        }
    
        public function setLastName($lastname)
        {
            $this->lastName = $lastname;
        }
    
        public function getLastName() 
        {
            return $this->lastName;
        }
    
        public function setCity($city)
        {
            $this->city = $city;
    
        }
    
        public function getCity()
        {
            return $this->city;
        }
    
    }
    
    $emply = new Employee();
    $emply->setFirstName("Peter");
    $emply->setLastName("Goomes");
    $emply->setCity("xyz");
    echo "FirstName:"; echo($emply->getFirstName());echo "<br>";
    echo "LastName:";  echo($emply->getLastName());echo "<br>";
    echo "City:";      echo($emply->getCity());
    
    OUTPUT:
    
    FirstName:Peter
    LastName:Goomes
    City:xyz
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: