使用PHP魔术方法实现属性的set、get方法

之前对PHP中的魔术方法一直有了解,但是对于具体的使用场景则是模模糊糊的。今天了解到了一种使用魔术方法的场景,整理了一下写出来。

假如一个类中具有较多的变量,对于每一个变量编写set/get方法是一件非常繁琐的事情,尤其对于数据库的查询结果,有时候字段可以很多。但是直接让程序调用类中的字段又不被推荐,这时候可以通过对__get、__set和__call方法的使用来解决这个问题。

<?php

class Basic {

	protected $_properties;

	/**
	 * Basic constructor.
	 * @param $val
	 */
	public function __construct ($val = array()) {
		$this->_properties = $val;
	}

	/**
	 * @param $key
	 * @param $val
	 */
	public function __set ($key, $val) {
		$this->_properties[$key] = $val;
	}

	/**
	 * @param $key
	 * @return
	 */
	public function __get ($key) {
		return isset($this->_properties[$key]) ? $this->_properties[$key] : null;
	}

	/**
	 * @param $_method
	 * @param $args
	 * @return
	 */
	public function __call ($_method, $args) {
		if(method_exists($this, $_method)) {
			return $this->$_method($args);
		}
		if(substr($_method, 0, 3) == 'get') {
			return $this->_get($_method);
		}
		if(substr($_method, 0, 3) == 'set') {
			$this->_set($_method, $args);
		}
		return null;
	}

	/**
	 * @param $_method
	 * @return
	 */
	private function _get ($_method) {
		$_method = substr($_method, 3, strlen($_method));
		$key     = implode('_', preg_split('#(?=[A-Z])#', lcfirst($_method)));
		$key     = strtolower($key);
		return isset($this->_properties[$key]) ? $this->_properties[$key] : null;
	}

	/**
	 * @param      $_method
	 * @param null $args
	 */
	private function _set ($_method, $args = null) {
		$_method                 = substr($_method, 3, strlen($_method));
		$key                     = implode('_', preg_split('#(?=[A-Z])#', lcfirst($_method)));
		$key                     = strtolower($key);
		$this->_properties[$key] = $args[0];
	}

}

$student = array(
	'name'  => '张三',
	'age'   => 18,
	'sex'   => 'male',
	'score' => 99
);
$basic   = new Basic($student);

$basic->level = 'A';

var_dump($basic->name);//string(6) "张三"
var_dump($basic->getLevel());//string(1) "A"
$basic->setLevel('B');
var_dump($basic->level);//string(1) "B"

通过代码中的方式,相当于对于每个字段默认实现了get/set方法,在对象中可以直接通过getKeyName和setKeyName方法的方式来操作对象的字段值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值