Make $_SESSION work as session_register

Asked

Viewed 523 times

0

I changed my session_register for $_SESSION, meanwhile $_SESSION does not allow me to use the variable in the same way session_register.

For being deprecated I thought they corresponded to the same thing. However the use after the declaration is quite different, session variables generated by session_register can be used normally, pluses for $_SESSION cannot.

$nome = "Haxz";
session_register("nome");

After the statement, simply using $nome it already returns the value. As a common variable.

$_SESSION["nome"] = "Haxz";

Does not allow me to use the variable as $nome, only as $_SESSION["nome"].

What puzzles me is that both can be tested the same way isset($_SESSION["nome"]) and in the print_r($_SESSION), are shown equal.

I don’t want to change my whole project (it’s pretty big) How to make the $_SESSION["nome"] answer equal to session_register("nome") ? (answer in order to be able to work with only one variable $nome correspondent.)

1 answer

3


Don’t do this.

Just do it at the end of the code:

    $_SESSION['nome'] = $nome;

And at first recover with

    $nome = $_SESSION['nome'];


...But if you really want to do it, one solution would be this:

function meu_session_register($nome){
    global $$nome;
    $_SESSION[$nome] = $$nome;
    $$nome = &$_SESSION[$nome]; 
}

Explanation:

  • first, we declare a global variable with the same $nome of the variable;

  • then we save in the session the value

  • then we re-assign the value to the variable by passing by reference (&), for subsequent changes to change the session value.

  • So, in fact $_SESSION is not a newer version of session_register... I thought there was something even wrong with php.ini. Thank you.

  • @Haxz session_register already works with $_SESSION, they are interfaces to the same structure. $_SESSION has been around for a while. For $_SESSION you already accessed the data of a session_register of your applications.

  • I understand. I was worried about the Notice and I ended up confusing the structure... Thank you very much, I will use this function A LOT.

  • @Haxz, I wish you didn’t need the job anymore. Seriously, if you get used to taking the session variables at the beginning, and save them after using, you’ll even get a better view of your code. Meanwhile, prefix them all with "$session_", so you can at least separate what is session and what is not.

  • The problem is not this, the project is already in the middle of the way (I’m actually updating) and there will be no way to change everything to $_SESSION.

Browser other questions tagged

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