<?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()函数
以上就介绍了 PHP类中 __set 和 _get的用法示例,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号