The visibility of a property ( public , private and protected ) is part of Concealment Concept >, which is important for achieving greater data consistency.
For example, the code below:
class Db_Table {
public $dbAdapter;
public function __constructor( Db_Adapter $dbAdapter ) {
$this -> dbAdapter = $dbAdapter;
}
}
Nothing prevents Cletus's asshole from catching this code from doing something like:
$this -> dbAdapter = 'Oi, eu sou o Goku!';
And send the pro space code by defining an anime endpoint in what should be an object that implements an interface to the database or extends that superclass.
This problem is resolved by changing the visibility of the property and creating a setter :
class Db_Table {
private $dbAdapter;
public function __constructor( Db_Adapter $dbAdapter ) {
$this -> setAdapter( $adapter );
}
public function setAdapter( Db_Adapter $dbAdapter ) {
$this -> dbAdapter = $dbAdapter;
return $this;
}
}
And the code is now foolproof because the DB_Table :: $ dbAdapter property will invariably be an instance of Db_Adapter .
In addition setting the visibility of a property with private without a set set makes it read-only in the context of the object.
>
However, you can yes manipulate the private and protected visibility property value through Reflection :
$obj = new Db_Table( new Db_Adapter );
try {
$reflector = new ReflectionProperty( 'Db_Table', 'dbAdapter' );
$reflector -> setAccessible( TRUE );
$reflector -> setValue( $obj, 'Oi, eu sou Goku!' );
var_dump( $reflector, $obj );
} catch( ReflectionException $e ) {
echo $e -> getMessage();
}
Though Reflection does not serve this purpose. u
Encapsulation is already a totally different animal. It involves the principle of code reuse (DRY - Do not Repeat Yourself) that does not exist only in Object Orientation.
Of course, simply creating a function to store a repetitive piece of code is already a form of encapsulation.
The difference is that with Object Orientation we have inheritance, composition, polymorphism, and all these strange words that elevates the potential of the encapsulation to the maximum of its potential.
Finally, the Validation you mentioned, already covered by the examples, is only possible through a setter because you can not have polymorphism or even conditionals in a public property. They accept whatever happens to them.
Original Author: Henrique Barcelos