批改状态:未批改
老师批语:
__get():用来获取私有成员和保护成员属性值的,有一个参数,参数传入你要获取的成员属性的名称,返回获取的属性值
__set():用来为私有和保护成员成员属性设置值的,有两个参数,第一个参数为你要为设置值的属性名,第二个参数是要给属性设置的值,没有返回值
test.php
<?php
require 'testclass.php';
$test = new test('php',30,['html','css','js']);
echo 'lang:'.$test->name.'<br>';
echo 'lang1:'.$test->lang1.'<br>';
echo 'lang2:'.print_r($test->lang2,true).'<br>';
echo 'lang3:'.$test->lang3.'<br>';
echo '<hr>';
$test->name = 'java';
$test->lang1 = 34;
$test->lang2 = ['test','test1','test2'];
echo 'lang:'.$test->name.'<br>';
echo 'lang1:'.$test->lang1.'<br>';
echo 'lang2:'.print_r($test->lang2,true).'<br>';
$test->lang3 = 'json';
echo 'lang3:'.$test->lang3.'<br>';
echo '<hr>';
$test->lang4 = 'mysql';
echo 'custom:<pre>'.print_r($test->data,true).'</pre>';点击 "运行实例" 按钮查看在线实例
testclass.php
<?php
class test{
private $name;
private $lang1;
private $lang2;
private $data=[];
public function __construct($name='',$lang1=3,array $lang2=[]){
$this->$name = $name;
$this->$lang1 = $lang1;
$this->$lang2 = $lang2;
}
public function __get($name){
$msg = null;
if(isset($this->$name)){
$msg = $this->$name;
}else if(isset($this->data[$name])){
$msg = $this->data[$name];
}else{
$msg = 'error';
}
return $msg;
}
public function __set($name,$value){
if(isset($this->$name)){
$this->$name = $value;
} else {
$this->data[$name] = $value;
}
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号