Usage examples of __set and _get in PHP classes

WBOY
Release: 2016-07-28 08:29:43
Original
970 people have browsed it
<?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()函数
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template