php variable scope resolution

Asked

Viewed 34 times

-3

I’m not able to understand how the scope of variables works in php, I try to use a variable, declared outside a function, inside this and it is null

 $DSN = $dsn;
    echo $DSN;
    function insert_in_DB($query){
        echo $DSN;

in case the echo above works, but the echo below does not

2 answers

2

In PHP the functions are not automatically closures, so the functions do not have access to outside variables unless they are declared as global within the function, or explicitly declared as closure, listing the variables outside that it should have access to.

But in general it is more recommended to pass the value to the function rather than to appeal to global variables.

-2

Does not work for 2 reasons:

  1. Your function is wrong (key not closed);
  2. Function defined, but not called.

To work it should be:

<?php
$dsn = 'algo'; //Não constava
$DSN = $dsn;
echo $DSN;
function insert_in_DB($query) {
  echo $DSN;
}

insert_in_DB('algo aqui'); //A saída será: 'algo'
  • 1

    Justifying my downvote: https://ideone.com/7MGmEH

Browser other questions tagged

You are not signed in. Login or sign up in order to post.