search
HomeBackend DevelopmentPHP Tutorialphp _set _get _isset _unset用法防被忽悠分析

php __set __get __isset __unset用法防被忽悠分析

大家好我是小烟  今天分享下 php面向对象中__set __get __isset __unset用法之防忽悠介绍

全文注意=====================================

__set __get __isset __unset  这些方法 老版本php是可以设置成私有的 但是现在php版本 最好不要设置成私有 更不能设置成静态 设置成静态方法直接就出错了  设置成私有的话 虽然能正常返回值 但是会有个 Warning 警告!!(本人是php5.5版本)



正文开始======================================


我们经常会在php的面向对象中可以看到位__set __get __isset __unset这些东西的用法,但很不明白为什么会要用这些东西,下面我们来一一介绍一下他们哥四的用法吧。

  一般来说,总是把类的属性定义为private,这更符合现实的逻辑。但是,对属性的读取和赋值操作是非常频繁的,因此在PHP5中,预定义了两个函数“__get()”和“__set()”来获取和赋值其属性,以及检查属性的“__isset()”和删除属性的方法“__unset()”。


我们为每个属性做了设置和获取的方法,在PHP5中给我们提供了专门为属性设置值和获取值的方法,“__set()”和“__get()”这两个方法,这两个方法不是默认存在的,而是我们手工添加到类里面去的,像构造方法(__construct())一样, 类里面添加了才会存在,可以按下面的方式来添加这两个方法,当然也可以按个人的风格来添加:

public function __get($property_name){    if(isset($this->$property_name)){    	return($this->$property_name);    }else{    	return(NULL);    }}//__set()方法用来设置私有属性public function __set($property_name, $value){	$this->$property_name = $value;}
__get()方法:这个方法用来获取私有成员属性值的,有一个参数,参数传入你要获取的成员属性的名称,返回获取的属性值,这个方法不用我们手工的去调用,因为我们也可以把这个方法做成私有的方法,是在直接获取私有属性的时候对象自动调用的。因为私有属性已经被封装上了,是不能直接获取值的(比如:"echo $p1->name"这样直接获取是错误的),但是如果你在类里面加上了这个方法,在使用"echo $p1->name"这样的语句直接获取值的时候就会自动调用__get($property_name)方法,将属性name传给参数$property_name,通过这个方法的内部执行,返回我们传入的私有属性的值。如果成员属性不封装成私有的,对象本身就不会去自动调用这个方法。

 基本上网上 99%的文章 介绍 __get() 都是这么说的 但是我还要说最关键的是  __get() 不光只是获取当前类的私有成员变量 还能在这个方法里面 做其他操作 比如说 实例化另一个类 获取另一个类的对象。 请看下面代码

  public function __get($name) {            return \Libs\Components::getInstance()->$name;    }

这里 如果 获取name  并不是获取当前类的 私有属性 而且静态调用 Components类 里面的 $name 属性 所以 __get 方法一定要灵活运用 还有就是 __get() 方法不只是调用当前类的私有变量

public function  __get($name) {		if(isset($this->config[$name])) {			return $this->config[$name];		}		return null;	}
也还能这么用   指定 要获取的 变量!!


甚至 还能在类里面用 请看下面代码

class b {	private $config = ['aa'=>'小烟'];	public function  __get($key) {		if($this->config[$key]) return $this->config[$key];	}	public function __construct() {		echo $this->aa;	}	}$b = new b();  //输出 小烟 

类里面 $this->bb 根本不存在 就会在类里面触发 __get 方法 返回config 里面的 aa  从而返回内容



__set()方法:这个方法也是用来获得你指定的变量 一般来讲都是获取类里面的私有变量,有两个参数,第一个参数为你要为设置值的属性名,第二个参数是要给属性设置的值,没有返回值。,

如果没有__set()这个方法,是不允许直接获取私有变量的,比如:$this->name='zhangsan', 这样会出错,但是如果你在类里面加上了__set($property_name, $value)这个方法,在直接给私有属性赋值的时候,就会自动调用它,把属性比如name传给$property_name, 把要赋的值"zhangsan"传给$value,通过这个方法的执行,达到赋值的目的。如果成员属性不封装成私有的,对象本身就不会去自动调用这个方法。为了不传入非法的值,还可以在这个方法给做一下判断。代码如下:

<?php class Person{	private $name;	private $sex;	private $age;	private	function __get($property_name){		echo "在直接获取私有属性值的时候,自动调用了这个__get()方法<br>";		if (isset($this->$property_name)) {			return ($this->$property_name);		} else {			return null;		}	}	private	function __set($property_name, $value) {		echo "在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值<br>";		$this->$property_name = $value;	}}$p1 = new Person();$p1->name = "小烟";$p1->sex = "男";$p1->age = 23;echo "姓名:".$p1->name."<br>";echo "性别:".$p1->sex."<br>";echo "年龄:".$p1->age."<br>"; 

程序执行结果:
在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值在直接获取私有属性值的时候,自动调用了这个__get()方法姓名:小烟在直接获取私有属性值的时候,自动调用了这个__get()方法性别:男在直接获取私有属性值的时候,自动调用了这个__get()方法年龄:23


以上代码如果不加上__get()和__set()方法,程序就会出错,因为不能在类的外部操作私有成员,而上面的代码是通过自动调用__get()和__set()方法来帮助我们直接存取封装的私有成员的。


__isset() 方法:在看这个方法之前我们看一下"isset()"函数的应用,isset()是测定变量是否设定用的函数,传入一个变量作为参数,如果传入的变量存在则传回true,否则传回false。


那么如果在一个对象外面使用"isset()"这个函数去测定对象里面的成员是否被设定可不可以用它呢?分两种情况,如果对象里面成员是公有的,我们就可以使用这个函数来测定成员属性,如果是私有的成员属性,这个函数就不起作用了,原因就是因为私有的被封装了,在外部不可见。那么我们就不可以在对象的外部使用"isset()"函数来测定私有成员属性是否被设定了呢?

答案是可以的,你只要在类里面加上一个"__isset()"方法就可以了,当在类外部使用"isset()"函数来测定对象里面的私有成员是否被设定时,就会自动调用类里面的"__isset()"方法了帮我们完成这样的操作,"__isset()"方法也可以做成私有的。你可以在类里面加上下面这样的代码就可以了:


private function __isset($nm){    echo "当在类外部使用isset()函数测定私有成员$nm时,自动调用<br>";    return isset($this->$nm);}

__unset()方法:看这个方法之前呢,我们也先来看一下"unset()"这个函数,"unset()"这个函数的作用是删除指定的变量且传回true,参数为要删除的变量。那么如果在一个对象外部去删除对象内部的成员属性用"unset()"函数可不可以呢,也是分两种情况,如果一个对象里面的成员属性是公有的,就可以使用这个函数在对象外面删除对象的公有属性,如果对象的成员属性是私有的,我使用这个函数就没有权限去删除,但同样如果你在一个对象里面加上"__unset()"这个方法,就可以在对象的外部去删除对象的私有成员属性了。


在对象里面加上了"__unset()"这个方法之后,在对象外部使用"unset()"函数删除对象内部的私有成员属性时,自动调用"__unset()"函数来帮
我们删除对象内部的私有成员属性,这个方法也可以在类的内部定义成私有的。在对象里面加上下面的代码就可以了:

private   function __unset($nm){	echo "当在类外部使用unset()函数来删除私有成员时自动调用的<br>";	unset($this->$nm);}

最后,我们来看一个完整的实例:

<?phpclass Person {	private $name;	private $sex;	private $age;	public function __get($property_name) {		if(isset($this->$property_name))		{			return ($this->$property_name);		} else {			return (NULL);		}	}	public function __set($property_name, $value) {		$this->$property_name = $value;	}	public  function __isset($nm) {		echo "isset()函数测定私有成员时,自动调用<br>";		return isset($this->$nm);	}	public  function __unset($nm) {		echo "当在类外部使用unset()函数来删除私有成员时自动调用的<br>";		unset($this->$nm);	}}$p1 = new Person();$p1->name = "this is a person name";echo var_dump(isset($p1->name))."<br>";echo $p1->name."<br>";unset($p1->name);echo $p1->name;



输出结果为:
isset()函数测定私有成员时,自动调用 
bool(true) 
this is a person name
当在类外部使用unset()函数来删除私有成员时自动调用的

isset()函数测定私有成员时,自动调用


最后最后 小烟还是要提醒下你 这四个方法用法都是非常的灵活的 不要以为只能获取类里面的私有变量 而且可以自由扩展 获取类里某个特定成员变量的值 或者 其他类里面的值切记切记  不要被误导!!

小烟 2014-12-03     转载请注明出处 谢谢!


Statement
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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools