如何从类变量数组中访问类成员?

发布于 2024-08-22 03:28:46 字数 548 浏览 1 评论 0原文

我想使用 PHP 的反射功能从方法中检索参数名称列表。我有一个这样的类:

class TestClass {
    public function method($id, $person, $someotherparam) {
        return;
    }
}

我可以使用这样的代码获取列表:

$r = new ReflectionClass('TestClass');

$methods = $r->getMethods();

foreach($methods as $method) {
    $params = $method->getParameters();
    $p = $params[0]; // how can I combine this and the next line?
    echo $p->name;

我想知道如何从数组访问类成员,所以我不必进行分配。这可能吗?我尝试了类似 echo ($params[0])->name 但出现错误。

I want to use PHP's reflection features to retrieve a list of parameter names from a method. I have a class like this:

class TestClass {
    public function method($id, $person, $someotherparam) {
        return;
    }
}

I can get the list using code like this:

$r = new ReflectionClass('TestClass');

$methods = $r->getMethods();

foreach($methods as $method) {
    $params = $method->getParameters();
    $p = $params[0]; // how can I combine this and the next line?
    echo $p->name;

I want to know how to access the class members from the array, so I don't have to do an assignment. Is this possible? I tried something like echo ($params[0])->name but I get an error.

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

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

发布评论

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

评论(1

笑,眼淚并存 2024-08-29 03:28:46

您可以将这两行 : 替换

$p = $params[0]; // how can I combine this and the next line?
echo $p->name;

为单行 : ,

echo $params[0]->name;

即此处不需要任何类型的括号。

但你不能使用这种语法:

($params[0])->name

它会给你一个

Parse error: syntax error, unexpected T_OBJECT_OPERATOR

you can replace these two lines :

$p = $params[0]; // how can I combine this and the next line?
echo $p->name;

by that single one :

echo $params[0]->name;

i.e. no need for any kind of parenthesis here.

But you cannot use this kind of syntax :

($params[0])->name

It'll give you a

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