Home Backend Development PHP Tutorial PHP中__get()和__set()的用法实例详解_PHP

PHP中__get()和__set()的用法实例详解_PHP

Jun 01, 2016 pm 12:06 PM
get set

php面向对象_get(),_set()的用法
一般来说,总是把类的属性定义为private,这更符合现实的逻辑。但是,对属性的读取和赋值操作是非常频繁的,因此在PHP5中,预定义了两个函数“__get()”和“__set()”来获取和赋值其属性。类似于java中的javabean的操作,使用的方法也类似,只是不需要像javabean中那样,对每个字段进行set和get的操作。只需要加上两个魔术方法即可。即私有成员的设值和取值的操作。在PHP5中给我们提供了专门为属性设置值和获取值的方法,“__set()”和“__get()”这两个方法,这两个方法不是默认存在的,而是我们手工添加到类里面去的,像构造方法(__construct())一样,类里面添加了才会存在,可以按下面的方式来添加这两个方法,当然也可以按个人的风格来添加:
复制代码 代码如下:
//__set()方法用来设置私有属性
public function __set($name,$value){
$this->$name = $value;
}
//__get()方法用来获取私有属性
public function __get($name){
return $this->$name;
}

__get()方法:这个方法用来获取私有成员属性值的,有一个参数,参数传入你要获取的成员属性的名称,返回获取的属性值,这个方法不用我们手工的去调用,因为我们也可以把这个方法做成私有的方法,是在直接获取私有属性的时候对象自动调用的。因为私有属性已经被封装上了,是不能直接获取值的,但是如果你在类里面加上了这个方法,在使用“echo$p1->name”这样的语句直接获取值的时候就会自动调用__get($name)方法,将属性name传给参数$name,通过这个方法的内部执行,返回我们传入的私有属性的值。如果成员属性不封装成私有的,对象本身就不会去自动调用这个方法。

__set()方法:这个方法用来为私有成员属性设置值的,有两个参数,第一个参数为你要为设置值的属性名,第二个参数是要给属性设置的值,没有返回值。这个方法同样不用我们手工去调用,它也可以做成私有的,是在直接设置私有属性值的时候自动调用的,同样属性私有的已经被封装上
了,如果没有__set()这个方法,是不允许的,比如:$this->name=‘zhangsan',这样会出错,但是如果你在类里面加上了__set($property_name, $value)这个方法,在直接给私有属性赋值的时候,就会自动调用它,把属性比如name传给$property_name,把要赋的值“zhangsan”传给$value,通过这个方法的执行,达到赋值的目的。如果成员属性不封装成私有的,对象本身就不会去自动调用这个方法。为了不传入非法的值,还可以在这个方法给做一下判断。代码如下:
复制代码 代码如下:
class Person
{
//下面是人的成员属性,都是封装的私有成员
private $name; //人的名子
private $sex; //人的性别
private $age; //人的年龄
//__get()方法用来获取私有属性
private function __get($property_name)
{
echo "在直接获取私有属性值的时候,自动调用了这个__get()方法
";
if(isset($this->$property_name))
{
return($this->$property_name);
}
else
{
return(NULL);
}
}
//__set()方法用来设置私有属性
private function __set($property_name, $value)
{
echo "在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值
";
$this->$property_name = $value;
}
}
$p1=newPerson();
//直接为私有属性赋值的操作,会自动调用__set()方法进行赋值
$p1->name="张三";
$p1->sex="男";
$p1->age=20;
//直接获取私有属性的值,会自动调用__get()方法,返回成员属性的值
echo "姓名:".$p1->name."
";
echo "性别:".$p1->sex."
";
echo "年龄:".$p1->age."
";
?>

程序执行结果:
在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值
在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值
在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值
在直接获取私有属性值的时候,自动调用了这个__get()方法
姓名:张三
在直接获取私有属性值的时候,自动调用了这个__get()方法
性别:男
在直接获取私有属性值的时候,自动调用了这个__get()方法
年龄:20
以上代码如果不加上__get()和__set()方法,程序就会出错,因为不能在类的外部操作私有成员,而上面的代码是通过自动调用__get()和__set()方法来帮助我们直接存取封装的私有成员的。
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

How to automate tasks using PowerShell How to automate tasks using PowerShell Feb 20, 2024 pm 01:51 PM

If you are an IT administrator or technology expert, you must be aware of the importance of automation. Especially for Windows users, Microsoft PowerShell is one of the best automation tools. Microsoft offers a variety of tools for your automation needs, without the need to install third-party applications. This guide will detail how to leverage PowerShell to automate tasks. What is a PowerShell script? If you have experience using PowerShell, you may have used commands to configure your operating system. A script is a collection of these commands in a .ps1 file. .ps1 files contain scripts executed by PowerShell, such as basic Get-Help

How does java initiate an http request and call the post and get interfaces? How does java initiate an http request and call the post and get interfaces? May 16, 2023 pm 07:53 PM

1. Java calls post interface 1. Use URLConnection or HttpURLConnection that comes with java. There is no need to download other jar packages. Call URLConnection. If the interface response code is modified by the server, the return message cannot be received. It can only be received when the response code is correct. to return publicstaticStringsendPost(Stringurl,Stringparam){OutputStreamWriterout=null;BufferedReaderin=null;StringBuilderresult=newSt

How to delete elements from set in javascript How to delete elements from set in javascript Jan 12, 2022 am 10:56 AM

Methods to delete elements: 1. Use delete() to delete the specified element from the Set object, the syntax is "setObj.delete(value);"; 2. Use clear() to delete all elements in the Set object, the syntax is "setObj.delete(value);" "setObj.clear();".

Example of Curl Get command Example of Curl Get command Mar 20, 2024 pm 06:56 PM

In Linux, URL or Curl client is a popular command line utility that allows you to transfer data over the network using various protocols such as HTTPS, HTTP, FTP, etc. It allows you to send and receive data using its get, post and request methods. Among them, you need to use the "get" method frequently. Therefore, it becomes crucial to learn various methods and various options that you can use to increase your productivity. "Performing a curl operation is as simple as entering a few simple commands. Although it seems simple, many users do not fully realize its potential. Therefore, this short guide provides some information on how to perform curl operations on Linux systems. Example using the "curlget" command." Curl

How to change Ubuntu's apt-get update source? How to change Ubuntu's apt-get update source? Jan 05, 2024 pm 03:40 PM

Manually modify Ubuntu's apt-get source 1. Use the ssh tool to connect to Ubuntu (I use xshell) 2. Type cd/etc/apt/3 on the command line and back up the source.list file in this directory (you must have sudo permissions) ), then there is a source.list.bak file. 4. Clear the source.list file content (note: it cannot be restored after clearing, so you need to perform the previous step to back up the file in advance). At this time, use sudo to prompt that the permissions are insufficient. Switch directly to the root user and execute this command. 5. Use vim to open source.list, press the i key to enter the editing mode, paste the source address to be modified, and then press

In-depth analysis of the similarities and differences between the get method and post method in jQuery In-depth analysis of the similarities and differences between the get method and post method in jQuery Feb 24, 2024 pm 12:15 PM

Get and post are two commonly used ajax request methods in jQuery, which are used to send requests to the server and obtain data. They have some differences in usage and some features. Next we will explain their similarities and differences in detail, and attach specific code examples. The similarities between get and post: they are both methods for sending ajax requests. You can obtain data from the server by specifying the URL and data parameters. Both can accept callback functions as parameters, which are used to process data returned by the server or handle failed requests.

Inventory of common uses of dict and set in Python programming Inventory of common uses of dict and set in Python programming Jul 25, 2023 pm 04:52 PM

This article is based on the basics of Python and introduces how to use dict and set. The dict using the key-value storage structure is very useful in Python. It is important to choose an immutable object as the key. The most commonly used key is a string.

See all articles