Last active
January 4, 2016 21:39
-
-
Save mugyu/8681927 to your computer and use it in GitHub Desktop.
php で未定義のプロパティに値をセットしたりゲットしたり。これで ruby みたいな getter や setter が作れる。けど面倒くさいなぁ
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
<? | |
class Hoge | |
{ | |
private $message = 'hello, world!'; | |
function __get($var) | |
{ | |
switch ($var) { | |
case 'message': | |
print $this->message . PHP_EOL; | |
break; | |
default: | |
$class_name = get_class($this); | |
print "Undefined property: $class_name:$var" . PHP_EOL; | |
} | |
} | |
function __set($var, $val) | |
{ | |
switch ($var) { | |
case 'message': | |
$this->message = $val; | |
break; | |
default: | |
$class_name = get_class($this); | |
print "Undefined property: $class_name:$var" . PHP_EOL; | |
} | |
} | |
} | |
$hoge = new Hoge(); | |
$hoge->message; | |
$hoge->message = 'bood by!'; | |
$hoge->message; | |
$hoge->non_property; | |
$hoge->non_property = 'hoge'; | |
#hello, world! | |
#bood by! | |
#Undefined property: Hoge:non_property | |
#Undefined property: Hoge:non_property |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment