// NOTE: __get will trigger for getting private or unknow properties, __set will trigger for setting private or unknow properties. Best practice is to not use them.
a) Using __get and __set for getting and setting private property
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
}
}
$myClass = new MyClass();
$myClass->firstField = "This is a foo line";
$myClass->secondField = "This is a bar line";
echo $myClass->firstField;
echo $myClass->secondField;
/* Output:
This is a foo line
This is a bar line
*/
b) __GET and __SET triggers for unknow property
class MyClass {
//private $firstField;
//private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
} else { return 'getting unknow property' . PHP_EOL;}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
} else { echo ' setting unknown property' . PHP_EOL;}
}
}
$myClass = new MyClass();
$myClass->firstField = "This is a foo line";
$myClass->secondField = "This is a bar line";
echo $myClass->firstField;
echo $myClass->secondField;
/* Output:
setting unknown property
setting unknown property
getting unknow property
getting unknow property
*/
b) Using traditional setters and getters
class MyClass {
private $firstField;
private $secondField;
public function getFirstField() {
return $this->firstField;
}
public function setFirstField($firstField) {
$this->firstField = $firstField;
}
public function getSecondField() {
return $this->secondField;
}
public function setSecondField($secondField) {
$this->secondField = $secondField;
}
}
$myClass = new MyClass();
$myClass->setFirstField("This is a foo line");
$myClass->setSecondField("This is a bar line");
echo $myClass->getFirstField();
echo $myClass->getSecondField();
/* Output:
This is a foo line
This is a bar line
*/
No comments:
Post a Comment