Accessing objects in PHP on other pages [closed]

0

I'm starting to program with object orientation in PHP. I came across the following problem: I have a Usuario class and I need to access the object as soon as I log in to the site, but when I try to access the object and the function of other pages, it gives an error.

How do I access the object on another page?

$Usuario->metodo();

we have the user class and soon down

    <?php
 include_once("Conexao.php"); 
 class Usuario extends Conexao
 {  
    private  $id;
    private  $nome;
    private  $senha;
    private  $sessao;

    function setSessao($sessao){
        $this->sessao = $sessao;
     }...

the manager page that I instantiate and the user class and login

<?php
    $usuario = new Usuario();       

    $usuario->logar();
?>

the index class which I want to use the instantiated object on the manager page

<?php
     echo "<h1>".$usuario->getNome()."</h1>";
?>

The error that appears is this: Notice: Undefined variable: user in

C:\xampp\htdocs\ConstrutoresFree\MyBiz\index.php on line 221

Fatal error: Uncaught Error: Call to a member function getNome() on null in C:\xampp\htdocs\ConstrutoresFree\MyBiz\index.php:221 Stack trace: #0 {main} thrown in C:\xampp\htdocs\ConstrutoresFree\MyBiz\index.php on line 221

(thanks for the tips)

    
asked by anonymous 25.08.2017 / 13:51

1 answer

2

More simply, you can store the created instance of your Usuario object in a session (PHP Documentation for session functions) and access them on the desired page. See below:

While on page Gerente.php

<?php
    $usuario = new Usuario();       

    $usuario->logar();
?>

Make:

<?php
    session_start();

    $usuario          = new Usuario();       
    $_SESSION['User'] = $usuario;

    $usuario->logar();
?>

So, on the page index.php , you can access the instance of your object:

<?php
     echo "<h1>" . $_SESSION["User"]->getNome() . "</h1>";
?>

Or, on page index.php :

<?php
     $userObject = $_SESSION["User"];

     echo "<h1>" . $userObject->getNome() . "</h1>";
?>
    
25.08.2017 / 14:38