<?php class example { private $a; public function __set($a, $str) { //对输入进行验证。 if (strlen($str) > 0) { return $this->$a = $str; } else { //如果不能通过验证则抛出错误 throw new Exception( '字符串不能为空。'); } } public function __get($a) { return 'The words you entered: ' . $this->$a; } } $c = new example(); $c->a = 'Hello World!'; //此处将调用默认自动调用 __set()函数 echo $c->a; //<pre name="code" class="php">此处将调用默认自动调用 __get()函数
The above introduces the usage examples of __set and _get in PHP classes, including related content. I hope it will be helpful to friends who are interested in PHP tutorials.