#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2012
    Posts
    1
    Rep Power
    0

    PHP OOP and session


    Hi all.
    I am trying to execute the code in the below, but it returns nothing after second refresh of page. WHY?

    PHP Code:
    session_start();

    class 
    A{
    public function 
    getT(){
    return 
    "ttext ttext ttext";
    }
    }
    if(isset(
    $_SESSION['classA']))
    echo 
    $_SESSION['classA']->getT();

    $_SESSION['classA'] = new A();
    echo 
    $_SESSION['classA']->getT(); 

    Thanks.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2003
    Posts
    3,600
    Rep Power
    595
    For me it does the same thing every time, as expected.

    ttext ttext ttextttext ttext ttext

    There is no difference between doing a refresh and loading the page the first time. Perhaps you have a caching issue.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  4. #3
  5. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,316
    Rep Power
    7171
    The code works for me as expected as well.

    If you're storing objects in a session you have to be 100% sure that your class definition is loaded before you call session_start().

    For example, with a minor tweak your code will generate a fatal error and not output anything after you refresh the page:
    Code:
    <?php
    session_start();
    
    if(true){
    class A{
    public function getT(){
    return "ttext ttext ttext";
    }
    }
    }
    if(isset($_SESSION['classA']))
    echo $_SESSION['classA']->getT();
    
    $_SESSION['classA'] = new A();
    echo $_SESSION['classA']->getT();
    If you have session auto start enabled in your php.ini file you *might* hit this error even with your original code. You should check that.

    If you enable display_error and error_reporting it should be obvious if this error is occurring.
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around

IMN logo majestic logo threadwatch logo seochat tools logo