<?php
class SportObject
{
private $type = ' ';
public function getType(){
return $this -> type;
}
private function __get($name){
if(isset($this ->$name)){
echo '变量'.$name.'的值为:'.$this -> $name.'<br>';
}
else{
echo '变量'.$name.'未定义,初始化为0<br>';
$this->$name=0;
}
}
private function __set($name, $value){
if(isset($this -> $name)){
$this -> $name=$value;
echo '变量'.$name.'赋值为:'.$value.'<br>';
}else{
$this -> $name = $value;
echo '变量'.$name.'被初始化为:'.$value.'<br>';
}
}
}
$MyComputer = new SportObject(); $MyComputer -> name;
?>
以上输出结果如下:
变量name未定义,初始化为0
变量name被初始化为:0
我知道当执行$MyComputer -> name时,会调用__get()方法,但是根据输出结果可知除了调用__get()方法外还调用了__set()方法,请问这是怎么回事?
class SportObject
{
private $type = ' ';
public function getType(){
return $this -> type;
}
private function __get($name){
if(isset($this ->$name)){
echo '变量'.$name.'的值为:'.$this -> $name.'<br>';
}
else{
echo '变量'.$name.'未定义,初始化为0<br>';
$this->$name=0;
}
}
private function __set($name, $value){
if(isset($this -> $name)){
$this -> $name=$value;
echo '变量'.$name.'赋值为:'.$value.'<br>';
}else{
$this -> $name = $value;
echo '变量'.$name.'被初始化为:'.$value.'<br>';
}
}
}
$MyComputer = new SportObject(); $MyComputer -> name;
?>
以上输出结果如下:
变量name未定义,初始化为0
变量name被初始化为:0
我知道当执行$MyComputer -> name时,会调用__get()方法,但是根据输出结果可知除了调用__get()方法外还调用了__set()方法,请问这是怎么回事?