What is Encapsulation?
Posted by Raj
Encapsulation:
The wrapping of data and function together in a single unit(class) is called encapsulation.
In PHP 4 objects were little more than arrays.In PHP 5 you get much more control by visibility,
interfaces,and more.
PHP5 provides data-hiding capabilities with public, protected, and private data attributes and methods:
Public : A public variable or method can be accessed directly by any user of the class.
Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.
Private: private variable or method can only be accessed internally from the class in which it is defined.
E.g.:
class is a protective wrapper which binds data and methods together,they can be accessed only though object of that class.
Example:
<?php
class Shape {
private static $_circle;
public function Circle( ) {
if( $this->_circle == null ) {
$this->_circle = new Circle();
}
return $this->_circle;
}
}
class Circle {
private $_radius;
public function __construct() {
$this->_radius = "10";
}
public function GetRadius() {
return $this->_radius;
}
}
$shape= new Shape();
echo $shape->Circle()->GetRadius();
?>
The wrapping of data and function together in a single unit(class) is called encapsulation.
In PHP 4 objects were little more than arrays.In PHP 5 you get much more control by visibility,
interfaces,and more.
PHP5 provides data-hiding capabilities with public, protected, and private data attributes and methods:
Public : A public variable or method can be accessed directly by any user of the class.
Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.
Private: private variable or method can only be accessed internally from the class in which it is defined.
E.g.:
class is a protective wrapper which binds data and methods together,they can be accessed only though object of that class.
Example:
<?php
class Shape {
private static $_circle;
public function Circle( ) {
if( $this->_circle == null ) {
$this->_circle = new Circle();
}
return $this->_circle;
}
}
class Circle {
private $_radius;
public function __construct() {
$this->_radius = "10";
}
public function GetRadius() {
return $this->_radius;
}
}
$shape= new Shape();
echo $shape->Circle()->GetRadius();
?>
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under
OOP interview questions and answers,
PHP,
PHP interview questions and answers
.You can leave a response, or trackback from your own site.