Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
This post was edited and submitted for review 2 years ago and failed to reopen the post:
Original close reason(s) were not resolved
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(15)
您可以使用 php 魔术方法
__get
和__set
。You can use php magic methods
__get
and__set
.为什么要使用 getter 和 setter?
Why use getters and setters?
Google 已经发布了 PHP 优化指南,结论是:
没有 getter 和 setter 优化 PHP
不,您不能使用魔法方法。对于 PHP 来说,魔法方法是邪恶的。为什么?
PHP 不是 Java、C++ 或 C#。 PHP 是不同的,并且遵循不同的规则。
Google already published a guide on optimization of PHP and the conclusion was:
No getter and setter Optimizing PHP
And no, you must not use magic methods. For PHP, Magic Methods are evil. Why?
PHP is not Java, C++, or C#. PHP is different and plays with different rules.
封装在任何 OO 语言中都很重要,流行度与之无关。在动态类型语言(如 PHP)中,它特别有用,因为在不使用 setter 的情况下几乎没有方法可以确保属性属于特定类型。
在 PHP 中,这是有效的:
在 Java 中,则不然:
使用魔术方法(
__get
和__set
)也有效,但仅在访问可见性低于该属性的属性时有效。当前范围可以访问。如果使用不当,在尝试调试时很容易让您头疼。Encapsulation is important in any OO language, popularity has nothing to do with it. In dynamically typed languages, like PHP, it is especially useful because there is little ways to ensure a property is of a specific type without using setters.
In PHP, this works:
In Java, it doesn't:
Using magic methods (
__get
and__set
) also works, but only when accessing a property that has lower visibility than the current scope can access. It can easily give you headaches when trying to debug, if it is not used properly.如果您喜欢使用 __call 函数,则可以使用此方法。它与
$this->property()
$this->property($value)
$this->getProperty()
$this->setProperty($value)
kalsdas
If you preffer to use the __call function, you can use this method. It works with
$this->property()
$this->property($value)
$this->getProperty()
$this->setProperty($value)
kalsdas
除了这里已经很棒且受人尊敬的答案之外,我还想扩展一下没有 setter/getter 的 PHP。
PHP 没有 getter 和 setter 语法。正如 Dave 所指出的,它提供了子类或神奇方法来允许“挂钩”并覆盖属性查找过程。
Magic 允许我们这些懒惰的程序员做更多事情当我们积极参与一个项目并熟悉它时,代码会减少,但通常会牺牲可读性。
性能 每个不必要的函数(由于在 PHP 中强制使用类似 getter/setter 的代码架构而产生)在调用时都会涉及到自己的内存堆栈帧,并且会浪费 CPU 周期。
可读性:代码库会导致代码行膨胀,这会影响代码导航,因为更多的 LOC 意味着更多的滚动。
偏好:就我个人而言,根据我的经验,我认为静态代码分析的失败
只要当时我无法获得明显的长期利益,就可以作为避免走上神奇之路的标志。
谬误:
一个常见的论点是可读性。例如,
$someobject->width
比$someobject->width()
更容易阅读。然而,与行星的周长
或宽度
(可以假定为静态
)不同,对象的实例(例如$someobject
) > 需要宽度函数,可能需要测量对象的实例宽度。因此,可读性的增加主要是因为断言的命名方案,而不是通过隐藏输出给定属性值的函数。
__get / __set 使用:
属性值的预验证和预清理
字符串例如
<前><代码>”
一些 {mathsobj1->generatelatex} 多重
行文本 {mathsobj1->latexoutput}
{mathsobj1->generatelatex} 有很多变量
某种原因
”
在这种情况下
generatelatex
将遵循actionname + methodname特殊、明显的情况
注意: PHP 选择不实现 getter/setter 语法。我并不是说 getter/setter 通常都是不好的。
In addition to the already great and respected answers in here, I would like to expand on PHP having no setters/getters.
PHP does not have getter and setter syntax. It provides subclassed or magic methods to allow "hooking" and overriding the property lookup process, as pointed out by Dave.
Magic allows us lazy programmers to do more with less code at a time at which we are actively engaged in a project and know it intimately, but usually at the expense of readability.
Performance Every unnecessary function, that results from forcing a getter/setter-like code-architecture in PHP, involves its own memory stack-frame upon invocation and is wasting CPU cycles.
Readability: The codebase incurs bloating code-lines, which impacts code-navigation as more LOC mean more scrolling,.
Preference: Personally, as my rule of thumb, I take the failure of static code analysis
as a sign to avoid going down the magical road as long as obvious long-term benefits elude me at that time.
Fallacies:
A common argument is readability. For instance that
$someobject->width
is easier to read than$someobject->width()
. However unlike a planet'scircumference
orwidth
, which can be assumed to bestatic
, an object's instance such as$someobject
, which requires a width function, likely takes a measurement of the object's instance width.Therefore readability increases mainly because of assertive naming-schemes and not by hiding the function away that outputs a given property-value.
__get / __set uses:
pre-validation and pre-sanitation of property values
strings e.g.
In this case
generatelatex
would adhere to a naming scheme of actionname + methodnamespecial, obvious cases
Note: PHP chose not to implement getter/setter syntax. I am not claiming that getters/setter are generally bad.
准备好!
Ready!
我使用魔术方法 __call 做了一个实验。
不确定我是否应该发布它(因为其他答案和评论中的所有“不要使用魔法方法”警告)但我将把它留在这里......以防万一有人发现它有用。
只需在类中添加上面的方法,现在您可以输入:
这样您就可以获取/设置类中的所有内容(如果存在),因此,如果您仅需要少数特定元素,则可以使用“白名单”作为过滤器。
示例:
现在您只能获取/设置“foo”和“fee”。
您还可以使用该“白名单”来分配自定义名称以访问您的变量。
例如,
通过该列表,您现在可以输入:
.
.
.
就这样。
文档:
__call() 在调用不可访问的方法时触发对象上下文。
I made an experiment using the magic method __call.
Not sure if I should post it (because of all the "DO NOT USE MAGIC METHODS" warnings in the other answers and comments) but i'll leave it here.. just in case someone find it useful.
Just add that method above in your class, now you can type:
This way you can get/set everything in your class if it exist so, if you need it for only a few specific elements, you could use a "whitelist" as filter.
Example:
Now you can only get/set "foo" and "fee".
You can also use that "whitelist" to assign custom names to access to your vars.
For example,
With that list you can now type:
.
.
.
That's all.
Doc:
__call() is triggered when invoking inaccessible methods in an object context.
嗯,PHP 确实有神奇的方法
__get
、__set
、__isset
& 。__unset
,这始终是一个开始。唉,正确的(明白了吗?)OO 属性不仅仅是魔法方法。 PHP 实现的主要问题是为所有 不可访问的属性调用魔术方法。这意味着在确定 name 是否实际上是对象的属性时,您必须在魔术方法中重复自己(例如,通过调用 property_exists())。除非所有类都继承自 ie,否则您无法真正使用基类解决这个普遍问题。 ClassWithProperties,因为 PHP 缺乏多重继承。相比之下,Python新样式类为您提供
property()
,它允许您显式定义所有属性。 C# 有特殊的语法。http://en.wikipedia.org/wiki/Property_(programming)
Well, PHP does have magic methods
__get
,__set
,__isset
&__unset
, which is always a start. Alas proper (get it?) OO properties is more than magic methods. The main problem with PHP's implementation is that magic methods are called for all inaccessible properties. Which means you have to Repeat Yourself (eg. by calling property_exists()) in the magic methods when determining if name is actually a property of your object. And you can't really solve this general problem with a base class unless all your classes inherit from ie. ClassWithProperties, since PHP lacks multiple inheritance.In contrast, Python new style classes gives you
property()
, which lets you explicitly define all your properties. C# has special syntax.http://en.wikipedia.org/wiki/Property_(programming)
阅读完其他建议后,我倾向于这样说:
作为 GENERIC 规则,您不会总是为 ALL 属性定义设置器,特别是“内部”属性(信号量) ,内部标志...)。显然,只读属性不会有 setter,因此某些属性只会有 getter;这就是 __get() 缩小代码的地方:
是的!我们也可以编写一个私有方法来做到这一点,但话又说回来,我们将声明许多方法(++内存),最终会调用另一个始终相同的方法。为什么不编写一个SINGLE方法来统治它们...? [是的!双关语绝对是故意的! :)]
魔术设置器也可以仅响应特定属性,因此可以仅在一种方法中针对无效值筛选所有日期类型属性。如果日期类型属性在数组中列出,则可以轻松定义它们的设置器。当然,这只是一个例子。有太多的情况。
关于可读性...嗯...这是另一场争论:我不喜欢被 IDE 的使用所束缚(事实上,我不使用它们,它们倾向于告诉我(并且强迫我)如何编写......并且我喜欢编码“美”)。我倾向于在命名方面保持一致,因此使用 ctags 和其他一些辅助工具对我来说就足够了......无论如何:一旦完成所有这些神奇的 setter 和 getter,我会编写其他过于具体或“特殊”的 setter可以概括为 __set() 方法。这涵盖了我需要的有关获取和设置属性的所有内容。当然:并不总是有共同点,或者有一些属性不值得编写一个神奇的方法,然后仍然是古老的良好的传统 setter/getter 对。
编程语言就是:人类人工语言。因此,它们中的每一个都有自己的语调或重音、语法和风格,因此我不会假装使用与 Java 或 C# 相同的“重音”来编写 Ruby 或 Python 代码,也不会编写类似的 JavaScript 或 PHP Perl 或 SQL...按其应有的方式使用它们。
After reading the other advices, I'm inclined to say that:
As a GENERIC rule, you will not always define setters for ALL properties, specially "internal" ones (semaphores, internal flags...). Read-only properties will not have setters, obviously, so some properties will only have getters; that's where __get() comes to shrink the code:
Yes! we could write a private method to do that, also, but then again, we'll have MANY methods declared (++memory) that end up calling another, always the same, method. Why just not write a SINGLE method to rule them all...? [yep! pun absolutely intended! :)]
Magic setters can also respond ONLY to specific properties, so all date type properties can be screened against invalid values in one method alone. If date type properties were listed in an array, their setters can be defined easily. Just an example, of course. there are way too many situations.
About readability... Well... That's another debate: I don't like to be bound to the uses of an IDE (in fact, I don't use them, they tend to tell me (and force me) how to write... and I have my likes about coding "beauty"). I tend to be consistent about naming, so using ctags and a couple of other aids is sufficient to me... Anyway: once all this magic setters and getters are done, I write the other setters that are too specific or "special" to be generalized in a __set() method. And that covers all I need about getting and setting properties. Of course: there's not always a common ground, or there are such a few properties that is not worth the trouble of coding a magical method, and then there's still the old good traditional setter/getter pair.
Programming languages are just that: human artificial languages. So, each of them has its own intonation or accent, syntax and flavor, so I won't pretend to write a Ruby or Python code using the same "accent" than Java or C#, nor I would write a JavaScript or PHP to resemble Perl or SQL... Use them the way they're meant to be used.
一般来说,第一种方式总体上更受欢迎,因为那些具有编程知识的人可以轻松过渡到 PHP 并以面向对象的方式完成工作。第一种方式更为通用。我的建议是坚持在多种语言中经过尝试和正确的做法。然后,当您使用另一种语言时,您将准备好完成一些事情(而不是花时间重新发明轮子)。
Generally speaking, the first way is more popular overall because those with prior programming knowledge can easily transition to PHP and get work done in an object-oriented fashion. The first way is more universal. My advice would be to stick with what is tried and true across many languages. Then, when and if you use another language, you'll be ready to get something accomplished (instead of spending time reinventing the wheel).
在 netbeans 约定中创建源代码的方法有很多。这很好。它让思考变得更容易===错。只需使用传统方法,特别是当您不确定应该封装哪一项属性以及不应该封装哪一项属性时。我知道,这是一个 boi.... pla... 代码,但对于调试工作和许多其他人来说,这是更好、更清晰的方法。不要花太多时间研究如何制作简单的 getter 和 setter 的数千种艺术。如果你使用魔法,你就不能实现太多的设计模式,比如德米特规则等等。在特定情况下,您可以使用 magic_calls 或小型、快速且清晰的解决方案。当然,您也可以通过这种方式为设计模式制定解决方案,但为什么会让您的生活变得更加困难。
There are many ways to create sourcecode in a netbeans-convention. This is nice. It makes thinks such easyer === FALSE. Just use the traditionel, specially if you are not sure which one of the properties should be encapsuled and which one not. I know, it is a boi.... pla... code, but for debugging-works and many other thinks it is the better, clear way. Dont spend to much time with thousend of arts how to make simple getters and setters. You cannot implement too some design patterns like the demeter-rule and so on, if you use magics. In specific situation you can use magic_calls or for small, fast and clear solutions. Sure you could make solutions for design-patters in this way too, but why to make you live more difficult.
验证 + 格式化/导出值
Setters 让您验证数据,getters 让您格式化或导出数据。对象允许您将数据及其验证和格式化代码封装到一个鼓励 DRY 的整洁包中。
例如,考虑以下包含出生日期的简单类。
您需要验证所设置的值是否为
,并且您不想在整个应用程序(或就此而言的多个应用程序)上进行此验证。相反,将成员变量设置为受保护或私有(以便使 setter 成为唯一的访问点)并在 setter 中进行验证会更容易,因为这样您就会知道该对象包含有效的出生日期,无论该对象的哪一部分对象来自的应用程序,如果您想添加更多验证,则可以将其添加在一个位置。
您可能希望添加对同一成员变量进行操作的多个格式化程序,即
getAge()
和getDaysUntilBirthday()
,并且您可能希望在getBirthDate 中强制执行可配置格式()
取决于区域设置。因此,我更喜欢通过 getters 一致地访问值,而不是将$date->getAge()
与$date->birth_date
混合在一起。当您扩展对象时,getter 和 setter 也很有用。例如,假设您的应用程序需要在某些地方允许 150 年以上的出生日期,但在其他地方则不允许。在不重复任何代码的情况下解决问题的一种方法是扩展 BirthDate 对象并将附加验证放入 setter 中。
Validating + Formatting/Deriving Values
Setters let you to validate data and getters let you format or derive data. Objects allow you to encapsulate data and its validation and formatting code into a neat package that encourages DRY.
For example, consider the following simple class that contains a birth date.
You'll want to validate that the value being set is
And you don't want to do this validation all over your application (or over multiple applications for that matter). Instead, it's easier to make the member variable protected or private (in order to make the setter the only access point) and to validate in the setter because then you'll know that the object contains a valid birth date no matter which part of the application the object came from and if you want to add more validation then you can add it in a single place.
You might want to add multiple formatters that operate on the same member variable i.e.
getAge()
andgetDaysUntilBirthday()
and you might want to enforce a configurable format ingetBirthDate()
depending on locale. Therefore I prefer consistently accessing values via getters as opposed to mixing$date->getAge()
with$date->birth_date
.getters and setters are also useful when you extend objects. For example, suppose your application needed to allow 150+ year birth dates in some places but not in others. One way to solve the problem without repeating any code would be to extend the
BirthDate
object and put the additional validation in the setter.这篇文章并不是专门讨论
__get
和__set
而是__call
,除了方法调用之外,它们的想法是相同的。一般来说,由于评论和帖子中概述的原因,我会远离任何类型的允许重载的魔术方法但是,我最近遇到了我使用的第 3 方 API,它使用 SERVICE和子服务,例如:其中重要的部分是,除了子操作之外,该 API 具有相同的所有内容,在本例中为
doActionOne
。这个想法是,开发人员(我自己和其他使用此类的人)可以通过名称调用子服务,而不是像这样:我可以这样做:
硬编码这只会导致大量重复(这个例子非常 与代码大致相似):
但是通过
__call()
的神奇方法,我能够使用动态方法访问所有服务:这种动态调用返回数据的好处是如果供应商添加另一个子服务,我不必在类中添加另一个方法或创建扩展类等。我不确定这对任何人是否有用,但我想我会展示一个示例,其中
__set
、__get
、__call
等可能是一个可以考虑的选项,因为主要功能是返回数据。编辑:
巧合的是,我在发布几天后看到了这个,它准确地概述了我的情况。这不是我指的 API,但方法的应用是相同的:
我使用 api正确吗?
This post is not specifically about
__get
and__set
but rather__call
which is the same idea except for method calling. As a rule, I stay away from any type of magic methods that allow for overloading for reasons outlined in the comments and posts HOWEVER, I recently ran into a 3rd-party API that I use which uses a SERVICE and a SUB-SERVICE, example:The important part of this is that this API has everything the same except the sub-action, in this case
doActionOne
. The idea is that the developer (myself and others using this class) could call the sub-service by name as opposed to something like:I could do instead:
To hardcode this would just be a lot of duplication (this example very loosely resembles the code):
But with the magic method of
__call()
I am able to access all services with dynamic methods:The benefit of this dynamic calling for the return of data is that if the vendor adds another sub-service, I do not have to add another method into the class or create an extended class, etc. I am not sure if this is useful to anyone, but I figured I would show an example where
__set
,__get
,__call
, etc. may be an option for consideration since the primary function is the return of data.EDIT:
Coincidentally, I saw this a few days after posting which outlines exactly my scenario. It is not the API I was referring to but the application of the methods is identical:
Am I using api correctly?
更新:不要使用这个答案,因为这是我在学习时发现的非常愚蠢的代码。只需使用普通的 getter 和 setter,就好多了。
我通常使用该变量名作为函数名,并向该函数添加可选参数,以便当调用者填充该可选参数时,然后将其设置为属性并返回 $this 对象(链接),然后当该可选参数未指定时呼叫者,我只是将财产返回给呼叫者。
我的例子:
Update: Don't use this answer since this is very dumb code that I found while I learn. Just use plain getter and setter, it's much better.
I usually using that variable name as function name, and add optional parameter to that function so when that optional parameter is filled by caller, then set it to the property and return $this object (chaining) and then when that optional parameter not specified by caller, i just return the property to the caller.
My example: