Example code of _get method and _set method access method in php

不言
Release: 2023-04-03 14:42:01
Original
2115 people have browsed it

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."&emsp;性别:".$people1->gender."<br/>";     //_get 函数被调用
    echo "姓名:".$people2->name."&emsp;性别:".$people2->gender."&emsp;年龄:".$people2->age;
    /* 运行结果:
        姓名:张三 性别:男
        姓名:李四 性别:女 年龄:29
    */
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!