PHP properties with get/set functions
One of the handy features of other languages is the ability to create get and set methods for properties. In trying to find a good way to duplicate this functionality in PHP, I stumbled across this: http://www.php.net/manual/en/language.oop5.magic.php#98442
Here is my breakdown of that class:
<?php
class ObjectWithGetSetProperties {
public function __get($varName) {
if (method_exists($this,$MethodName='get_'.$varName)) {
return $this->$MethodName();
} else {
trigger_error($varName.' is not avaliable .',E_USER_ERROR);
}
}
public function __set($varName,$value) {
if (method_exists($this,$MethodName='set_'.$varName)) {
return $this->$MethodName($value);
} else {
trigger_error($varName.' is not avaliable .',E_USER_ERROR);
}
}
}
?>
My plan was to extend this class and define the appropriate get_someproperty()
and set_someproperty()
in this extended class.
<?php
class SomeNewClass extends ObjectWithGetSetProperties {
protected $_someproperty;
public function get_someproperty() {
return $this->_someproperty;
}
}
?>
The trouble is, the base class of ObjectWithGetSetProperties
is unable to see my method get_someproperty()
in SomeNewClass
. I always get the error, "key is not available".
Is there any way to resolve this, allowing the base class of ObjectWithGetSetProperties
to work, or will I have to create those __get()
and __set()
magic methods in each class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Try
is_callable
instead. Example code-fragment:(Updated to show where
B
overridesA
)That's not well documented (some mentions in the comments), but
method_exists()
really only checks for method presence in the current class.But you can use
is_callable()
instead. It also verifies that the method not only exists, but is indeed allowed to be invoked:In your example, you'll need to declare the
$_someproperty
property, like this