-
-
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 "
"; Copier après la connexion Copier après la connexion
- $p = new Person();
- if ( isset( $p->name ) ) {
- print $p->name;
- } else {
- print "nope\n";
- }
- 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 "
"; Copier après la connexion Copier après la connexion
- $p = new Person();
- $p->name = "bob";
- $p->age = 44;
- print_r( $p );
- unset($p->name);
- print_r( $p );
- print "";
- ?>
-
复制代码
输出结果:
Person Object
(
[_name:Person:private] => BOB
[_age:Person:private] => 44
)
Person Object
(
[_name:Person:private] =>
[_age:Person:private] => 44
)
|