LΞИIИ
LΞИIИ

Reputation: 1454

PHP: var from string in function no working

this function does not return the result, what could I be doing wrong?

<?php

function iisset($name){
    return ${$name}; // "${$name}" does not work
}
$hola = 1;
echo iisset("hello");

Note: it works correctly if it is not in a function

Upvotes: 0

Views: 220

Answers (1)

Michael Martone
Michael Martone

Reputation: 134

You have a few issues going on here. The first is an issue of scope. Nothing outside the function iisset($name) is normally visible to it. Therefore any variable defined outside iisset($name) can't been seen.

So the first step would be to make it global by adding global ${$name}; to the first line after the function declaration. The second would be that there is no variable named "hello" outside the function. If you are trying to access the $hola then I would recommend the following:

<?php
function iisset($name){
    global ${$name};
    return ${$name}; // "${$name}" does not work
}
$hola = 1;
echo iisset("hola");

Upvotes: 1

Related Questions