Home  >  Article  >  Backend Development  >  Usage examples of __set and _get in PHP classes

Usage examples of __set and _get in PHP classes

WBOY
WBOYOriginal
2016-07-28 08:29:43946browse
<?php

class example {
	
	private $a;
	
	public function __set($a, $str) {
		//对输入进行验证。
		if (strlen($str) > 0) {
			return $this->$a = $str;
		} else {
                        //如果不能通过验证则抛出错误
                        throw new Exception( '字符串不能为空。');
		}		
	}
	
	public function __get($a) {
		return 'The words you entered: ' . $this->$a;
	}	
}

$c = new example();

$c->a = 'Hello World!'; //此处将调用默认自动调用 __set()函数
echo $c->a; //<pre name="code" class="php">此处将调用默认自动调用 __get()函数

The above introduces the usage examples of __set and _get in PHP classes, including related content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn