This article introduces to you the example code of the _get method and _set method access method in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
<?php //访问方法 class guests{ public $name; public $gender; public $age; //使用_get _set,避免直接对类属性的访问 function _set($pro_name,$pro_value){ // _set(属性名,属性值) 必须含有两个参数 $this->$pro_name=$pro_value; //$this -> $属性名 = $属性值 } function _get($proName){ //_get方法 必须含有一个参数 return $this->$proName; } } $people1 = new guests(); //实例化 $people1->name="张三"; //_set 函数被调用 $people1->gender="男"; $people2 = new guests(); //实例化 $people2->name="李四"; $people2->gender="女"; $people2->age="29"; echo "姓名:".$people1->name." 性别:".$people1->gender."<br/>"; //_get 函数被调用 echo "姓名:".$people2->name." 性别:".$people2->gender." 年龄:".$people2->age; /* 运行结果: 姓名:张三 性别:男 姓名:李四 性别:女 年龄:29 */
Recommended related articles:
Introduction to the characteristics and usage of Trait in PHP (with code)
php implementation operation Summary of various ways to file (with code)
The above is the detailed content of Example code of _get method and _set method access method in php. For more information, please follow other related articles on the PHP Chinese website!