0

A im writing a simple script in PHP with few files, in 'loginForm.php' I have code:

<?php

session_start();

$login = $_GET['login'];
$password = $_GET['password'];
$remember = $_GET['remember'];

include_once("login.php");
$userAccount = new UserAccount($login, $password);
$logged = $userAccount -> isLogged();
(...)

and in file 'photo.php':

global $userAccount;
$login = $userAccount -> getLogin();

what gives mi an error:

Call to a member function getLogin() on a non-object

I also tried with $GLOBALS - same result.

Mariusz Jucha
  • 141
  • 1
  • 3
  • 11
  • 1
    photo.php or login.php? besides, you don't need to add the global statement if both variables are in same scope which appears to be the case – Hanky Panky Nov 10 '13 at 16:13
  • in login.php is code of class UserAccount, in photo.php I tried to reach the global variable $userAccount form loginForm.php. – Mariusz Jucha Nov 10 '13 at 17:36

2 Answers2

0

Global variable does not work across requests, but have file scope.

the typical use of global variables if to have a variable that is accessible across different scopes (normally functions in the same file.

For example in file1.php

<?php

$value = 1;
echo $value;    // prints '1'

function f1() {
   global $value;
   $value++;
}

echo $value;    // prints '2'

function f1() {
   $value++;
}

echo $value;    // prints '2'

?>

To use variables across requests, use sessions.

safest way to create sessions in php

Storing objects in PHP session

Community
  • 1
  • 1
crafter
  • 6,246
  • 1
  • 34
  • 46
0

OK, now i did:

1) In AJAX-request file i create a instance of Class UserAccount, which will be store in $_SESSION array

<?php

include_once("login.php");
session_start();

$login = $_GET['login'];
$password = $_GET['password'];
$rememberMe = $_GET['remember'];

$userAccount = new UserAccount();
$userAccount -> LogIn($login, $password);
$logged = $userAccount -> isLogged();
$_SESSION['userAccountClassObject'] = serialize($userAccount);

2) In static (non AJAX-request) file 'photo.php' it works fine:

<?php

include_once("login.php");
$user = unserialize($_SESSION['userAccountClassObject']);
$login = $user -> getLogin();

3) But in other AJAX-request file - addComment.php unfortunatelly doesn't work:

<?php

$id = $_GET['id'];
$comment = $_GET['comment'];
session_start();
include("login.php");
$user = unserialize($_SESSION['userAccountClassObject']);
$login = $user -> getLogin(); // Fatal error
Mariusz Jucha
  • 141
  • 1
  • 3
  • 11
  • Serialising and unserializing objects is nit so straightfoward. You cannot reliably unserialise objects with certain data types, for example resources )think database connection) or closures. http://css.dzone.com/articles/how-correctly-work-php – crafter Nov 11 '13 at 09:55