魔法方法+反射 API = 无法调查类属性。为什么?

发布于 2024-08-30 04:23:19 字数 163 浏览 3 评论 0原文

如果我使用魔法的话。使用反射 API 时,我无法调查类属性。为什么会这样?

编辑

什么是Reflection API?请不要推荐我 php.net 我不明白..请用你的话引导我 plsss

If I use magic methods. While using reflection API, I can't investigate class properties.. Why is it so?

EDIT

What is Reflection API? pls do not refer me php.net i didnt understood that.. guide me in your words plsss

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

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

发布评论

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

评论(2

听不够的曲调 2024-09-06 04:23:19

使用魔术方法访问属性,这些属性通常不会出现在类的定义中。

您的类的定义通常如下所示:

class MyClass {
    private $data;
    public function __get($name) {
        return $this->data[$name];
    }
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

由于没有真正的属性——只有一个$data数组,它将被魔术方法__get使用>__set 作为一个大数据存储——反射 API 无法看到它们。

这是使用魔术方法引起的问题之一:它们用于访问不存在的属性(或方法,使用__call - 并且反射 API 只能看看那里有什么。

Using magic methods to access properties, those properties will generally not be present in the class' definition.

Your class' definition will generally look like this :

class MyClass {
    private $data;
    public function __get($name) {
        return $this->data[$name];
    }
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

As there is no real properties -- there is on only a $data array, which will be used by the magic methods __get an __set as a big data-store -- those cannot be seen by the Reflection API.

That's one of the problems caused by using magic methods : they are used to access properties (or methods, with __call) which are not there -- and the Reflection API can only see what's there.

痕至 2024-09-06 04:23:19

一个可能的解决方案可能是增加受保护的 $data 的范围:

class MyClass {
    protected $data;
    public function __get($name) {
        return $this->data[$name];
    }
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

这样,扩展类就可以访问它们认为合适的数组并收集运行时定义的属性。

A possible solution might be to increase the scope of $data to protected:

class MyClass {
    protected $data;
    public function __get($name) {
        return $this->data[$name];
    }
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

This way, extended classes can access the array as they see fit and collect runtime defined properties.

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