-
-
class person { - function __get( $property ) {
- $method = "get{$property}";
- if ( method_exists( $this, $method ) ) {
- return $this->$method();
- }
- }
function __isset( $property ) {
- $method = "get{$property}";
- return (method_exists( $this, $method ) );
- }
function getName() {
- return "Bob";
- }
-
- function getAge() {
- return 44;
- }
- }
- print "
";<li>$p = new Person();<li>if ( isset ( $p->name ) ) {<li> print $p->name;<li>} else {<li> print "nopen";<li>}<li>print " "; - // 出力:
- // ボブ
- ?>
-
复制代
演示代2:
-
-
- class person {
- private $_name;
- private $_age;
function __set( $property, $value ) {
- $method = "set{$property}";
- if (method_exists( $this, $method ) ) {
- return $this->$method( $value );
- }
- }
-
- function __unset( $property ) {
- $method = "set{$property}";
- if (method_exists( $this, $method ) ) {
- $this->$method( null );
- }
- }
-
- function setName( $name ) {
- $this->_name = $name;
- if ( ! is_null( $name ) ) {
- $this->_name = strtoupper($this->_name) );
- }
- }
function setAge( $age ) {
- $this->_age = $age;
- }
- }
- print "
";</li>
<li>$p = new person();</li>
<li>$p->name = "ボブ";</li>
<li>$p->age = 44;</li>
<li>print_r( $p );</li>
<li>unset($p->name);</li>
<li>print_r( $p );</li>
<li>print " ";
- ?> ;
-
复制代
输出结果:
人物オブジェクト
(
[_name:個人:プライベート] => ボブ
[_年齢:人物:非公開] => 44
)
人物オブジェクト
(
[_name:個人:プライベート] =>
[_年齢:人物:非公開] => 44
)
|