首页上一页 1 下一页尾页 1 条记录 1/1页
php从入门到精通 第三版 魔术方法 __set() __get()例子
发表在PHP图书答疑
2014-09-15
是否精华
是
否
版块置顶:
是
否
Warning: The magic method __get() must have public visibility and cannot be static in
C:\ …………xxx.php on line 29
Warning: The magic method __set() must have public visibility and cannot be static in
C:\ …………xxx on line 37
----------------------------------------
下列例子 运行 有如上警告!!
在网上看了下,魔术方法 不能使 private
要用public 管理员解释下!
---------------------------------------
<?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 -> type = 'DIY';
$MyComputer -> type;
$MyComputer -> name;
?>
------------------------------------------------
C:\ …………xxx.php on line 29
Warning: The magic method __set() must have public visibility and cannot be static in
C:\ …………xxx on line 37
----------------------------------------
下列例子 运行 有如上警告!!
在网上看了下,魔术方法 不能使 private
要用public 管理员解释下!
---------------------------------------
<?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 -> type = 'DIY';
$MyComputer -> type;
$MyComputer -> name;
?>
------------------------------------------------