我何时/应该在PHP中使用__construct(),__get(),__set()和__call()? [英] When do/should I use __construct(), __get(), __set(), and __call() in PHP?

查看:100
本文介绍了我何时/应该在PHP中使用__construct(),__get(),__set()和__call()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个类似的问题讨论了__construct ,但我离开了在我的标题中,以供搜寻此内容的人搜索.

A similar question discusses __construct, but I left it in my title for people searching who find this one.

显然,__get和__set带有一个参数,该参数是要获取或设置的变量.但是,您必须知道变量名(例如,知道该人的年龄是$ age而不是$ myAge).因此,如果您必须知道变量名,尤其是在使用不熟悉的代码(例如库)时,我看不出要点.

Apparently, __get and __set take a parameter that is the variable being gotten or set. However, you have to know the variable name (eg, know that the age of the person is $age instead of $myAge). So I don't see the point if you HAVE to know a variable name, especially if you are working with code that you aren't familiar with (such as a library).

我发现一些页面解释 __get() __set()

I found some pages that explain __get(), __set(), and __call(), but I still don't get why or when they are useful.

推荐答案

此页面可能会有用. (请注意,您说的是不正确的-__set()将变量名和值都作为参数.__get()仅将变量名作为参数.)

This page will probably be useful. (Note that what you say is incorrect - __set() takes as a parameter both the name of the variable and the value. __get() just takes the name of the variable).

__get()__set()在要提供对变量的常规访问的库函数中很有用.例如,在ActiveRecord类中,您可能希望人们能够访问数据库字段作为对象属性.例如,在Kohana PHP框架中,您可以使用:

__get() and __set() are useful in library functions where you want to provide generic access to variables. For example in an ActiveRecord class, you might want people to be able to access database fields as object properties. For example, in Kohana PHP framework you might use:

$user = ORM::factory('user', 1);
$email = $user->email_address;

这是通过使用__get()__set()来完成的.

This is accomplished by using __get() and __set().

使用__call()时可以完成类似的操作,也就是说,您可以检测到何时有人在调用getProperty()和setProperty()并进行相应的处理.

Something similar can be accomplished when using __call(), i.e. you can detect when someone is calling getProperty() and setProperty() and handle accordingly.

这篇关于我何时/应该在PHP中使用__construct(),__get(),__set()和__call()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆