php 戏法方法

Jun 13, 2016 am 10:38 AM
function gt isset name this

php 魔术方法

__construct()__set()__get()

__isset()__unset()

__autoload()

__call()

__clone()

__invoke()

__sleep()

__wakeup()

__construct()

构造方法: 在PHP中的构造方法要求不能进行构造方法的重载,即构造 方法只有一个.

?

function __construct($name="宋", $sex="", $age=1) { //构造方法在对象诞生时为成员属性赋初值      $this->name=$name;      $this->sex=$sex;      $this->age=$age;}
Copy after login

?说明:

?

? ? 1. 在一个类中,它只可能有一个构造方法.
? ? 2. 所默认的构造方法是public的,如果使用private的话,则会构成单例模式.

?

一般来说,总是把类的属性定义为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;}
Copy after login


?__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,通过这个方法的执行,达到赋值的目的。如果成员属性不封装成私有的,对象本身就不会去自动调用这个方法。为了不传入非法的值,还可以在这个方法给做一下判断。代码如下:

<?phpclass Person{    //下面是人的成员属性, 都是封装的私有成员    private $name;       //人的名子    private $sex;        //人的性别    private $age;        //人的年龄        //__get()方法用来获取私有属性    private function __get($property_name)    {        echo "在直接获取私有属性值的时候,自动调用了这个__get()方法<br>";        if (isset($this->$property_name))        {            return ($this->$property_name);        }        else        {            return (NULL);        }    }        //__set()方法用来设置私有属性    private function __set($property_name,$value)    {        echo"在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值<br>";             $this->$property_name=$value;    }}$p1=new Person();//直接为私有属性赋值的操作, 会自动调用__set()方法进行赋值$p1->name="张三";$p1->sex="男";$p1->age=20;//直接获取私有属性的值, 会自动调用__get()方法,返回成员属性的值echo"姓名:".$p1->name."<br>";echo"性别:".$p1->sex."<br>";echo"年龄:".$p1->age."<br>";?>
Copy after login
?程序执行结果:

在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值
在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值
在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值
在直接获取私有属性值的时候,自动调用了这个__get()方法
姓名:张三
在直接获取私有属性值的时候,自动调用了这个__get()方法
性别:男
在直接获取私有属性值的时候,自动调用了这个__get()方法
年龄:20


以上代码如果不加上__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);}
Copy after login

?

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

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

?我们来看一个完整的实例:

<?phpclass Person{    //下面是人的成员属性    private $name; //人的名子    private $sex; //人的性别    private $age; //人的年龄        //__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;    }        //__isset()方法    private function __isset($nm)    {        echo "isset()函数测定私有成员时,自动调用<br>";        return isset($this->$nm);    }        //__unset()方法    private 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;?>
Copy after login
?输出结果为:

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

bool(true)

this is a person name

当在类外部使用unset()函数来删除私有成员时自动调用的

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


__set()__get()__isset()__unset()这四个方法都是我们添加到对象里面的,在需要时自动调用的,来完成在对象外部对对象内部私有属性的操作。


__autoload()

//PHP4 写法,之前必须加载类文件

<?phpinclude_once "cls/clsA.php";include_once "cls/clsB.php";$obj_A = new clsA();$obj_B = new clsB();?>
Copy after login
?处理加载步骤为:?

1:加载类文件;
2:实例化类。?


//PHP5 使用__autoload()函数

<?php $obj_A = new clsA(); $obj_B = new clsB(); function __autoload($className){ include_once "cls/$className.php"; } ?>
Copy after login
?处理加载步骤为(使用autoload函数):?

1:创建对象(伪实例)?
2:调用__autoload函数,将伪实例的类名传入?
3:使用__autoload函数中,预先写好的加载规则进行加载类文件?
4:实例化对象(真实实例)?
因此,我们可以看出,对于PHP5的autoload函数,必须给定规则,否则一点用没有。

对于PHP5的__autoload函数的使用时需要注意或完成如下事情。?
1:__autoload函数是用在类外面,而不是在类里面的函数。(__autoload也是被PHP5保护的关键字之一)?
2:完成对__autoload函数加载规则的编码。?


如上,当知道A是在cls目录中,而B是在cls/cls目录中。则编写__autoload加载规则就是必要的。

<?php// PHP5 Used __autoload function $obj_A = new clsA(); // in "cls" directory! $obj_B = new clsB(); // in "cls/cls" directory! function __autoload($className){    if (strtolowwer($className) == "clsb")    {        require_once "cls/cls/$className.php";    }    else    {        include_once "cls/$className.php";    }}?>
Copy after login

?

__toString()

__toString()方法也是一样自动被调用的,是在直接输出对象引用时自动调用的, 前面我们讲过对象引用是一个指针,比如说:“$p=new Person()“中,$p就是一个引用,我们不能使用echo 直接输出$p, 这样会输出”Catchable fatal error: Object of class Person could not be converted to string“这样的错误,如果你在类里面定义了“__toString()”方法,在直接输出对象引用的时候,就不会产生错误,而是自动调用了”__toString()”方法, 输出“__toString()”方法中返回的字符,所以“__toString()”方法一定要有个返回值(return 语句).

<?phpclass TestClass{    public $foo;    public function __construct($foo) {        $this->foo = $foo;    }  //定义一个__toString方法,返加一个成员属性$foo    public function __toString() {        return $this->foo;    }}$class = new TestClass('Hello');//直接输出对象Cheap Sunglassesecho $class;?>
Copy after login

?上例输出:Hello


__call()

__call( $method, $arg_array ) 当调用一个未定义的方法是调用此访求这里的未定义的方法包括没有权限访问的方法

?

<?php//当试图调用类中一个不存在或者不可用的方法时,//会执行该类中的__call()__call()必须接受两个参数,//第一个参数存放方法名称,//第二个参数存放不存在的方法的参数(此参数会放在与该参数同名的数组中)class callclass{    function __call($method_name, $p)    {        echo "使用__call尝试调用一个不存在/不可用的成员方法<br>";        echo $method_name;        echo "<pre class="brush:php;toolbar:false">";        print_r($p);        echo "
Copy after login
"; }}$obj = new callclass();$obj->method(1, 2, "Hello", "HP");?>?输出:

?

使用__call尝试调用一个不存在/不可用的成员方法

method
Array
(
? ? [0] => 1
? ? [1] => 2
? ? [2] => Hello
? ? [3] => HP
)

?

?

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

Video Face Swap

Video Face Swap

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

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)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

PHP determines whether a specified key exists in an array PHP determines whether a specified key exists in an array Mar 21, 2024 pm 09:21 PM

This article will explain in detail how PHP determines whether a specified key exists in an array. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP determines whether a specified key exists in an array: In PHP, there are many ways to determine whether a specified key exists in an array: 1. Use the isset() function: isset($array[&quot;key&quot;]) This function returns a Boolean value, true if the specified key exists, false otherwise. 2. Use array_key_exists() function: array_key_exists(&quot;key&quot;,$arr

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

Detailed explanation of the role and function of the MySQL.proc table Detailed explanation of the role and function of the MySQL.proc table Mar 16, 2024 am 09:03 AM

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table

See all articles