Passing a variable to a method, I need to either create the same variable, or somehow transfer it inside the method.

function foo($array) { // Создать переменную $hello // Или скопировать/переместить } $hello = "Hello, world!"; foo($hello); 

Then I remembered the links. But in this situation:

 function foo(&$array) { // Тут мне только доступно $array, а не переменная $hello (см. выше) } 

How can I transfer or copy a variable?
PS It is only necessary and not otherwise :)

  • and what prevents to transfer the variable to the second parameter in the description of the function? - Edward
  • @Edward, hmm .. restriction on the use of parameters. Need to do with just one. - entithat
  • @Eduard, pass in one array, which will be all - Cyril Malyshev
  • @ Kirill Malyshev, yes, of course, that this is my second option, if I don’t find a solution how to do it with a single variable — not an array. - entithat
  • well, either get the name of the variable: ru.stackoverflow.com/questions/122070/… - Ravshan Abdulaev

1 answer 1

You can create an associative array, pass it as an argument to a user-defined function, in the body of which you can process this array using extract (). This will give you the desired variable in the locale:

 $array = ['hello' => 'Hello, world!']; foo($array); // Hello, world! function foo($array) { extract($array); echo $hello; } 
  • Yes, the idea is good, but I am looking for a problem that does not use an array. Example: $array="Hello"; - entithat
  • @entithat and what did not suit you with an array? If there is more than one value, then you cannot do without an array (or object). - Edward
  • I'm thinking about this and this - entithat
  • @entithat at the expense of global variables do not even think. Or pass an array, or several arguments to a function - that's all. - Edward
  • Very sorry. I was hoping that php would give such an opportunity .. Thank you :) - entithat