Access another function Session

I would like an access an array multiple Times For that purpose I store the array in Session array with following session declaration

$_SESSION['data'] = array();

Is there any Possible to use $_SESSION like common variable

Intially it calls a function index(), and click anoher button it sets formval = 1 and goes to function index2

  

<?php

new SampleController();
session_start();
class SampleController {
    public function __construct() {
        if (isset($_REQUEST['formval']) && $_REQUEST['formval'] == '1') {
            self::index2();
        } else {
            self::index();
        }
    }

    public function getfunc1() {
        $_SESSION['data'] = array();
        $datarray = array('0', '1', '2');
        $_SESSION['data'] = $datarray;
    }

    public function getfunc2() {
        print_r($_SESSION);
        $val = $_SESSION['data'];
    }
}

It Shows Like

Undefined variable: _SESSION

I expect to need to access the $_SESSION['data'] array

3 answers

  • answered 2019-04-15 06:27 prasanna puttaswamy

    You have add session start before class declaration. If session start is added inside the method then it gives Undefined variable: _SESSION. Either you have to add session_start is all the method or you can add session star at the start. Here is eample

    class Api
    {
        public function getName()
        {
            session_start();
            $data = array('name'=>'Ashoka P');
            $_SESSION['name'] = '1';
            echo json_encode($data);
    
        }   
    
        public function getAge()
        {
            echo '123';
        }
    }
    

    If you try to access getAge method in the above then it give undefined _SESSION error. Whereas below will not result in the error

    session_start();
    class Api
    {
        public function getName()
        {
            $data = array('name'=>'Ashoka P');
            $_SESSION['name'] = '1';
            echo json_encode($data);
    
        }   
    
        public function getAge()
        {
            echo '123';
        }
    }
    

  • answered 2019-04-15 06:49 Prince Kumar Dwivedi

    try this will work for you.

    <?php 
    session_start();
    
    class SampleController {
    
        public function getfunc1(){
            $datarray = array('0','1','2');
            $_SESSION['data'] = $datarray;
        }
    
        public function getfunc2(){
            return $_SESSION['data'];
        }
    
    }
    
    $SampleController = new SampleController();
    $SampleController->getfunc1();
    $data = $SampleController->getfunc2();
    print_r($data);
    

  • answered 2019-04-16 00:45 David Bray

    this is wrong

    new SampleController();
    session_start();
    

    start the session first

    session_start();
    new SampleController();