-
-
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>
<li>$p = new Person();</li>
<li>if ( isset( $p->name ) ) {</li>
<li> print $p->name;</li>
<li>} else {</li>
<li> print "nopen";</li>
<li>}</li>
<li>print " ";
- // output:
- // Bob
- ?>
-
复制代码
演示代码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 = "bob";</li>
<li>$p->age = 44;</li>
<li>print_r( $p );</li>
<li>unset($p->name);</li>
<li>print_r( $p );</li>
<li>print " ";
- ?>
-
复制代码
输出结果:
Person Object
(
[_name:Person:private] => BOB
[_age:Person:private] => 44
)
Person Object
(
[_name:Person:private] =>
[_age:Person:private] => 44
)
|