note 115095 deleted from language.oop5.overloading by cmb
| From: | cmb@php.net | Date: | Sun, 29 Dec 2019 10:12:05 +0000 |
| Subject: | note 115095 deleted from language.oop5.overloading by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213662@lists.php.net to get a copy of this message | ||
Note Submitter: cavetroll3000 at gmail dot com
----
If you need to also use the magic setter in your constructor, you may use this example:
<?php
class person {
private $name;
private $addr;
private $city;
function __construct($n,$a,$c) {
$this->__set('name', $n); // Pushing "name" through the
setter where it will be validated and sanitated.
$this->addr = $a; // Adress is not validated
$this->city = $c; // Neither is this...
// $this->__set('city',$c); // But this is...
}
public function __get($property) {if (property_exists($this, $property)) {return
$this->$property;}}
public function __set($property, $value) {
if (property_exists($this, $property)) {
echo "<pre>Setting $value</pre>";
// ... Clever code for sanitation...
if ($value == "Evil input from user"){
echo "<pre>Oh no! Bad user! Go sit in the
corner!</pre>";
$this->$property = null;
} else {
$this->$property = $value;
}
}
return $this;
}
}
$cathy = new person('Cathy','9 Dark and Twisty','Evil input from
user');
$cathy->name = "Kitty Kat";
echo "<pre>" . print_r($cathy,1) . "</pre>";
echo "<pre>" . $cathy->city . "</pre>";
?>
This code will output:
Setting Kitty Kat
person Object
(
[name:person:private] => Kitty Kat
[addr:person:private] => 9 Dark and Twisty
[city:person:private] => Evil input from user
)
Evil input from user
So it is important to push variables from the user through the setters even in the constructor.