重载的__get是否需要管理所有成员变量?
我正在为类创建一个 __get() 函数来控制对我的私有成员变量的访问。 我是否需要设计函数来处理所有可能的成员值读取,或者我不能为公共成员编写该函数吗? 另外,我假设继承此类的类将使用我的 __get() 函数来访问私有成员。
class ClassA{
private $collection = array();
public $value;
function __get($item){
return $collection[$item];
}
I am creating a __get() function for a class to control access to my private member variables. Do I need to design the function to handle all possible member value reads or can I not write it for members that are public? Also, I am assuming that classes that inherit this class will use my __get() function to access private members.
class ClassA{
private $collection = array();
public $value;
function __get($item){
return $collection[$item];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,你不知道。
是的,它会:
No, you don't.
And yes, it will:
那么,您的代码将在数组中未设置的私有项目上失败。 但话又说回来,您可以使用它作为处理数组内外内容的方法;
继承您的调用的类将使用此 __get(),但可以被覆盖,因此请使用parent::__construct() 来明确。 另请注意,这些不能是静态的。 进一步阅读。
Well, your code would fail on private items not set in your array. But then again, you can use this as a way to deal with what's in and out of your array, as such ;
Classes that inherit your calls will use this __get(), but can be overridden, so use parent::__construct() for explicity. Also note that these cannot be static. Further reading.
首先,PHP 在类定义中搜索属性名称并尝试返回其值。 如果没有属性 - PHP 会尝试调用 __get($var) ,在这里您可以返回任何您想要的内容。 对于那些了解类似 Java 的 getter/setter 的人来说,这是一个有点令人困惑的行为,您必须为要访问的每个类成员定义它们。
当您可以轻松地使用类似 Java 的 getter/setter 时,您可以编写如下内容:
然后通过定义自定义 getter/setter
并以这种方式访问已定义的方法来使用此代码:
First of all PHP searches for property name in class definition and tries to return its value. If there's no property - PHP tries to call __get($var) and here you can return anything you want. This is a little confusing behavior for those, who know Java-like getters/setters where you have to define them for every class member you want to access.
When it's comfortable to use Java-like getters/setters - you may write something like this:
and then use this code by defining custom getters/setters
and access to defined methods this way: