Home Backend Development PHP Tutorial 【转】php面向对象_get(),set()的用法

【转】php面向对象_get(),set()的用法

Jun 13, 2016 am 11:03 AM
get name private property set

【转】php面向对象_get(),_set()的用法

一般来说,总是把类的属性定义为private,这更符合现实的逻辑。但是,对属性的读取和赋值操作是非常频繁的,因此在PHP5中,预定义了两个函数“__get()”和“__set()”来获取和赋值其属性,以及检查属性的“__isset()”和删除属性的方法“__unset()”。
上一节中,我们为每个属性做了设置和获取的方法,在PHP5中给我们提供了专门为属性设置值和获取值的方法,“__set()”和“__get()”这两个方法,这两个方法不是默认存在的,而是我们手工添加到类里面去的,像构造方法(__construct())一样,?类里面添加了才会存在,可以按下面的方式来添加这两个方法,当然也可以按个人的风格来添加:
//__get()方法用来获取私有属性
private function?__get($property_name)
{
if(isset($this->$property_name))
{
return($this->$property_name);
}else
{
return(NULL);
}
}
//__set()方法用来设置私有属性
private function?__set($property_name,?$value)
{
$this->$property_name?=?$value;
}
__get()方法:这个方法用来获取私有成员属性值的,有一个参数,参数传入你要获取的成员属性的名称,返回获取的属性值,这个方法不用我们手工的去调用,因为我们也可以把这个方法做成私有的方法,是在直接获取私有属性的时候对象自动调用的。因为私有属性已经被封装上了,是不能直接获取值的(比如:“echo $p1->name这样直接获取是错误的),但是如果你在类里面加上了这个方法,在使用“echo $p1->name这样的语句直接获取值的时候就会自动调用__get($property_name)方法,将属性name传给参数$property_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=new?Person();
//直接为私有属性赋值的操作,会自动调用__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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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

PHP Notice: Trying to get property of non-object - Solution PHP Notice: Trying to get property of non-object - Solution Aug 17, 2023 am 09:27 AM

PHPNotice: Tryingtogetpropertyofnon-object-Solution During the PHP development process, we may encounter a common error message: Tryingtogetpropertyofnon-object (trying to get the property of a non-object). This error is usually caused when we try to access a property (or call a method) on a variable that is not an object type. This article will introduce you to this

Solution to PHP Notice: Undefined property: Solution to PHP Notice: Undefined property: Jun 22, 2023 pm 02:48 PM

When writing code in PHP, we may encounter the error message "Notice: Undefinedproperty". This error means that we are accessing an undefined property, usually because the property has not been initialized in the code. So, how to solve this problem? Here are a few possible solutions: Initialize properties This is the simplest way to solve this problem. Explicitly initializing a property in code ensures that it is defined before use. For example: class

What does private mean in java What does private mean in java Nov 24, 2022 pm 06:27 PM

In Java, private means "private" and is an access control modifier used to modify classes, properties and methods. Class members modified with private can only be accessed and modified by the methods of the class itself, and cannot be accessed and referenced by any other class (including subclasses of the class); therefore, the private modifier has the highest level of protection.

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

TypeError: Cannot read property 'XXX' of null in Vue, what should I do? TypeError: Cannot read property 'XXX' of null in Vue, what should I do? Nov 25, 2023 pm 01:21 PM

Vue is a popular JavaScript framework for building user interfaces. During the development process, we may encounter various errors and exceptions. One of the common errors is "TypeError:Cannotreadproperty'XXX'ofnull". In this article, we will explore the causes of this error and how to fix it. First, let’s understand the reason behind this error. When we try to access a property or method of an object, if the pair

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();".

See all articles