Skip to content

Instantly share code, notes, and snippets.

@toshimaru
Last active December 12, 2015 05:28
Show Gist options
  • Save toshimaru/4721470 to your computer and use it in GitHub Desktop.
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.
<?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