When we are talking about Object Oriented Programming (OOP), Encapsulation acts a major role. Here I am not going to describe what is Encapsulation, because there are lots of definition in the web rather than mine š Just have an idea, it ‘s information hiding from out side. In this post I am trying to show a simpleĀ programĀ where we can achieve Encapsulation in PHP and Java.
What I think is learning new thing from what we have already known is the best way of learning. So I am good in PHP rather than Java. Therefore first I will show you how can we approach Encapsulation in PHP. The attributes we want to hide from the out side is coded in a different file and I have named it as person_lib.php
Here is the content of that file;
... class person{ var $name; function set_name($new_name){ $this -> name = $new_name; } function get_name(){ return $this -> name; } } ...
When we are talking about Encapsulation, getter and setter methods are more common words. Because those are theĀ intermediate platform to talk to the outside.Ā Lets see how can we access that encapsulated name variable.
Here I want to create person objects, assign names for those objects in the index.php page. You can do that like below;
... include("person_lib.php"); ... $anuja = new person(); $arosha = new person; // parenthesis are optional $anuja -> set_name("Anuja"); $arosha -> set_name("Arosha"); **** "Name of the first person is " . $anuja -> get_name(); **** nl2br("\n"); **** "Name of the second person is " . $arosha -> get_name(); ...
Replace **** with “echo“. OOP concept is same for any programming language. The only difference is the syntax and names that we are using to address them. Now I am going to show you the same thing in Java.
First I have created Person.java class to store my encapsulate variable and the getter and setter methods.
package oop; public class Person { private String name; public String getName() { return name; } public void setName(String newName) { name = newName; } }
Compare this code with the code written in person_lib.php file. The following code is, how weĀ retrieveĀ those data. I have named it as Student.java and both files locate in the same package oop.
package oop; public class Student{ public static void main(String[] args) { Person std1 = new Person(); std1.setName("Anuja"); Person std2 = new Person(); std2.setName("Arosha"); System.out.println("Name of the first student is: " + std1.getName()); System.out.println("Name of the second student is: " + std2.getName()); } }
That is all that I want to show. Hope you will enjoy OOP š
There is a mistake in php class “person” above. In PHP, member variables have public access modifier if you didn’t explicitly said it as private or protected. So it should be correct as private $name or protected $name to implement encapsulation correctly.
Thanks Gihan. You are correct. It was my mistake.
var $name; should be private var $name;
Thanks again š