如何在没有反射的情况下检查方法或属性的可见性?

发布于 2025-01-01 15:53:53 字数 258 浏览 1 评论 0原文

我正在写一个简单的 php 框架。现在我需要一种更好的方法来检查方法或属性是私有的还是公共的。目前我正在使用 Reflection 类,但几乎每个属性访问都需要它。

我需要它来实现神奇的 __get ,如果其中有公共方法 getTestProperty() ,它允许您调用 $object->testProperty

我正在寻找另一种方法来做到这一点(因为性能)。有没有更快的可能?

I'm writing a simple php framwork. Now I need a better way to check if a method or property is private or public. Currently I'm using the Reflection class for that, but as it's needed on nearly every property access.

I need it for the magic __get which will allow you to call $object->testProperty if there's a public method getTestProperty() in it.

I'm looking for an other way to do this (because of the performance). Is there any faster possibility?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绮烟 2025-01-08 15:53:53

您可以使用 is_callable 来检查是否可以在对象上调用该方法:

is_callable(array($object, 'methodName'))

如果需要检查某些属性是否存在,请使用 property_exists

property_exists($someObject', 'userId')

最后还有method_exists

method_exists('someClass', 'someMethod');

You can use is_callable to check if the method can be called on the object:

is_callable(array($object, 'methodName'))

If you need to check for some property existence use property_exists:

property_exists($someObject', 'userId')

And finaly there are method_exists:

method_exists('someClass', 'someMethod');
∝单色的世界 2025-01-08 15:53:53

还有2个有用的功能:
bool method_exists(class_name_or_object,method_name) - 如果方法存在(公共甚至受保护和私有)或 false,则返回 true
array get_class_methods(class_name_or_object) - 返回类或对象的公共方法的数组

There is also 2 useful functions:
bool method_exists(class_name_or_object,method_name) - will return true if method exists (public and even protected and private) either false
array get_class_methods(class_name_or_object) - return array of public methods of class or object

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文