Blogger Information
Blog 35
fans 2
comment 0
visits 22792
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
__get和__set()的使用--2018年5月3日
小学僧的博客
Original
657 people have browsed it

__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;
		}
	}
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post