Pregunta

My php code looks like this:

$jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode(file_get_contents("data.config"), TRUE)), RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) 
{

    if($key == "user")
        $user = $val;
    else if($key == "pass")
        $pass = $val;
    else if($key == "server")
        $server = $val;
    else if($key == "data")
        $data = $val;
}

if(!empty($_GET) && isset($_GET['function'])) call_user_func($_GET['function']);
if(!empty($_POST) && isset($_POST['function'])) call_user_func($_POST['function']);

function dbcon()
{
    return new mysqli($server,$user,$pass,$data);
}

But when I call dbcon(), I get undefined variable: user and so forth for the other 3.
Why is this happening and how can I fix it?

¿Fue útil?

Solución

You should use global keyword for this:

function dbcon()
{
    global $server;
    global $user; ...
    return new mysqli($server,$user,$pass,$data);
}

But you should not to use global variables
Simple always inject all your dependencies

function dbcon($server,$user,$pass,$data);

for example, or better: function dbcon($options);

Or the best way is the OOP learn and write separate class for incapsulate all of this....

Some offtop.
Replace this:

if(!empty($_GET) && isset($_GET['function'])) call_user_func($_GET['function']);
if(!empty($_POST) && isset($_POST['function'])) call_user_func($_POST['function']);

with followed:

$allowed_foos = array('allowed_foo1', 'allowed_foo2');
if(
   !empty($_REQUEST) && 
   isset($_REQUEST['function']) && 
   in_array($_REQUEST['function'], $allowed_foos)
) 
  call_user_func($_REQUEST['function']);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top