[英]PHP override get set methods
Is it possible to override the get and set methods for parameters that I already have set? 是否可以覆盖我已经设置的参数的get和set方法? So every time I set a param I have access to work with it/ validate it? 因此,每次设置参数时,都可以使用/验证它吗?
class User {
public $username;
function custom_set($name, $value) {
if(strlen($value) < 5) {
return "not long enough";
} else {
$this->$name = $value;
}
}
}
$u = new User();
$u->username = "ted";
echo $u->username;
Outputs: "not long enough" 输出:“不够长”
This is a very simplified example that I just wrote out and probably contains errors, it's just to convey what I am trying to do. 这是我刚刚写的一个非常简化的示例,可能包含错误,仅用于传达我正在尝试做的事情。
Basically everytime I call $u->username = "anything";
基本上每次我叫$u->username = "anything";
I want the custom_set
method to be called. 我想调用custom_set
方法。
I don't want to do the validation in the constructor and I don't want to create separate methods like $u->setVal("ted");
我不想在构造函数中进行验证,也不想创建单独的方法,例如$u->setVal("ted");
Is this possible? 这可能吗?
Implement the __set
method. 实现__set
方法。 This is called when attempted to access inaccessible properties. 尝试访问不可访问的属性时,将调用此方法。
function __set($name, $value) {
$this->custom_set($name, $value);
}
Note, however, that $username
is a public property so this will not work unless it is declared private
or protected
. 但是请注意, $username
是公共属性,因此,除非将其声明为private
或protected
否则它将不起作用。
Make those attributes protected
or private
then __get
and __set
will be called and you can delegate to whatever logic you want. 将那些属性设置为protected
或private
然后将调用__get
和__set
,您可以委托给您想要的任何逻辑。
Personally, I have yet to see a case where i would consider using a public
property for anything. 就个人而言,我还没有看到我会考虑将public
财产用于任何事情的情况。
您是在说魔术方法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.