PHP PHP Getters和Setters

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP PHP Getters和Setters相关的知识,希望对你有一定的参考价值。

<?php

	class Person
	{
		private $first;
		private $last;
		
		public setName ($name)
		{
		
		}
		
		public getName ($name)
		{
		
		}
		
		public function __set ($name, $value)
		{
			$key = strtoupper(substr($name, 1)) . strtolower(substr($name, 0, 1));
			$setter = 'set' . $key;
			
			if (method_exists($this, $setter)) {
				$this->$setter($value);
				return $value;
			}
			
			trigger_error('Undefined property via ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE);
		}
		
		public function __get ($name)
		{
			$key = strtoupper(substr($name, 1)) . strtolower(substr($name, 0, 1));
			$getter = 'set' . $key;
			
			if (method_exists($this, $getter)) {
				return $this->$getter();
			}
			
			trigger_error('Undefined property via ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE);
		}
	}
	
?>

以上是关于PHP PHP Getters和Setters的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 和 vue axios get 方法返回 Getters & Setters?

JavaBean的getters和setters方法自动生成

JavaScript 跨浏览器Getters / Setters(包括IE)

python py__getters-setters.py

使用myeclipse的时候generate getters and setters出错

PHP 7 中属性的类型提示?