3

Recently I've been facing the issue to access the parameters via a ReflectionFunction that have been passed via the use() construct to a closure.

Example:

$var = 'test';
$var2 = 'test2';
$func = function()use($var,$var2) {
    echo $var;
};

$ref = new ReflectionFunction($func);
// Access the parameters here

How would I go on to solve this problem?

Xatenev
  • 6,383
  • 3
  • 18
  • 42

1 Answers1

2

It can be solved by accessing $ref->getStaticVariables().

Example:

<?php


$var = 'test';
$var2 = 'test2';
$func = function()use($var,$var2) {
    echo $var;
};

$ref = new ReflectionFunction($func);
var_dump($ref->getStaticVariables());

Output:

array(2) { ["var"]=> string(4) "test" ["var2"]=> string(5) "test2" }

Working testcase: https://3v4l.org/hDl07

Reference getStaticVariables(): http://php.net/manual/de/reflectionfunctionabstract.getstaticvariables.php

Xatenev
  • 6,383
  • 3
  • 18
  • 42
  • So you ask a questions and answer it within a minute? Why?? – samayo Jul 03 '17 at 14:13
  • @samayo Because there is no relevant question and answer to the topic on stackoverflow yet. (Atleast I wasn't able to find anything) – Xatenev Jul 03 '17 at 14:13
  • 1
    Then you should have wrote it [Documentation](https://stackoverflow.com/documentation) or in [References](https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) or at least give others 5 minutes to reply – samayo Jul 03 '17 at 14:16
  • 3
    @samayo self answers are ok. there is even a checkbox to write an answer while you ask a question. this is definitely an accepted practice on Stack Exchange, abiding by the rules™ – Félix Adriyel Gagnon-Grenier Jul 03 '17 at 14:18
  • Yes, but not within 2 minutes, before anyone gets to take a look or even reply. If you think you have an answer to a questions which you only asked yourself, it doesn't necessarily mean you have to share it here. By that logic, we could all ask and answer every little answer to a every question that are not posted here – samayo Jul 03 '17 at 14:20
  • 2
    yes, between 2 minutes, as I said, **there is even a checkbox which you can use to answer your question while your are asking it**. you really need to back down from this, it is totally fine to self answer. – Félix Adriyel Gagnon-Grenier Jul 03 '17 at 14:22
  • 2
    @samayo I am unsure if your trolling or if you really mean that in a serious way. If I think I have an answer to a question that affects PHP and a function of them and there is no entry to find on stackoverflow I will **definetly** post a question and **instantly** answer that, so others can find it and it may be helpful for them. Take one step away from only grinding reputation and instead atleast **try** to see it in a way to be helpful for other users. – Xatenev Jul 03 '17 at 14:22
  • 2
    Note that `getStaticVariables()` also includes `static $foo = "bar";`: https://3v4l.org/pf8mb#v560 – kelunik Jul 03 '17 at 14:40