Can I extract the return value of a function?

I noticed that in PHP extract(some_function()); will work the same way:

 $stuff = some_function(); extract($stuff); 

But in the PHP documentation, the argument to the extraction function has & thingy in front, and from what I know, that means you need to pass a variable to it.

+4
source share
3 answers

If the documentation is correct, this will lead to the strictest standard:

PHP Strict standards: only variables must be passed by reference

So, I think you found the error in the documentation. Congratulations.

EDIT

It still doesn't complain if you use it with EXTR_REFS as the second argument:

 ~โฏ php -a Interactive shell php > function a(){return array('pwet'=> 42);} php > extract(a(), EXTR_REFS); php > echo $pwet; 42 

This is strange, because references to variables defined inside a function do not make much sense to me. I think this is possible and was possibly introduced because of this option, but appears only in the document and is not applied in the code.

EDIT

I seem to be right, I found this comment in ext/standard/array.c (branches 5.3 and 5.4):

 /* var_array is passed by ref for the needs of EXTR_REFS (needs to * work on the original array to create refs to its members) * simulate pass_by_value if EXTR_REFS is not used */ 
+4
source

Ampersand passes the variable by reference, so when it is used in a function, you control the original object, not a new variable with the same value. The documentation tells you that if you pass a variable to the extract function, then the source object may be updated with this function in some way.

So the answer is yes, you need to pass a variable to this function.

+1
source

The argument parameter of the $var_array argument to the extract function is passed by reference (most likely) from a hold from older versions of PHP. Newer versions automatically pass arrays by reference.

The extract function creates a list of variables from the contents of a (potentially large) array and it is not recommended to pass data of this type by value.

In short, assign your array to a variable and pass it that way.

+1
source

Source: https://habr.com/ru/post/1382149/


All Articles