Last active
December 12, 2015 05:28
-
-
Save toshimaru/4721470 to your computer and use it in GitHub Desktop.
Normaly, PHP Object can have property freely. But I want to force Object to have the property. This implementation make it possible.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ForceProperty { | |
private $val; | |
public function __get($name) { | |
if (property_exists($this, $name)) { | |
return $this->$name; | |
} else { | |
throw new LogicException(sprintf('Undefined property: $%s', $name)); | |
} | |
} | |
public function __set($name, $value) { | |
if (property_exists($this, $name)) { | |
$this->$name = $value; | |
} else { | |
throw new LogicException(sprintf('Undefined property: $%s', $name)); | |
} | |
} | |
} | |
$fp = new ForceProperty(); | |
$fp->val = "foo"; | |
$fp->undefined = "var"; // => LogicException: Undefined property: $undefined | |
echo $fp->val; // => foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment