Is there a way in PHP to use persistent data as in Java EE? (sharing objects between PHP threads) without session nor cache/DB

前端 未结 4 701
广开言路
广开言路 2020-12-06 18:43

Is there a way in PHP to use \"out of session\" variables, which would not be loaded/unloaded at every connexion, like in a Java server ?

Please excuse me for the la

相关标签:
4条回答
  • 2020-12-06 18:49

    I think you can use $_SESSION['aConstantValueForEveryone'] that you can read it on every page on same domain.

    Consider to refer to it's manual.

    0 讨论(0)
  • 2020-12-06 18:50
    // First page
    session_id('same_session_id_for_all');
    session_start();
    $_SESSION['aConstantValueForEveryone'] = 'My Content';
    
    // Second page
    session_id('same_session_id_for_all');
    session_start();
    echo $_SESSION['aConstantValueForEveryone'];
    

    This works out of the box in PHP. Using the same session id (instead of an random user-uniqe string) to initialize the session for all visitors leads to a session which is the same for all users.


    Is it really necessary to use session to achieve the goal or wouldn't it better to use constants?

    There is no pure PHP way of sharing information across different threads in PHP! Except for an "external" file/database/servervariable/sessionfile solution.


    Since some commentators pointed out, that there is serialize/unserialize functionality for Session data which might break data on the transport, there is a solution: In PHP the serialize and unserialize functionality serialize_handler can be configured as needed. See https://www.php.net/manual/session.configuration.php#ini.session.serialize-handler It might be also interesting to have a look at the magic class methods __sleep() and __wakeup() they define how a object behaves on a serialize or unserialize request. https://www.php.net/manual/language.oop5.magic.php#object.sleep ... Since PHP 5.1 there is also a predefined Serializable interface available: https://www.php.net/manual/class.serializable.php

    0 讨论(0)
  • 2020-12-06 19:05

    You can declare a Variable in your .htaccess. For Example SetEnv APPLICATION_ENVIRONMENT production and access it in your application with the function getenv('APPLICATION_ENVIRONMENT')

    0 讨论(0)
  • 2020-12-06 19:09

    Another solution is to wrap your variable in a "persistent data" class that will automatically restore its data content every time the php script is run. Your class needs to to the following:

    • store content of variable into file in __destructor
    • load content of variable from file in __constructor

    I prefer storing the file in JSON format so the content can be easily examined for debugging, but that is optional.

    Be aware that some webservers will change the current working directory in the destructor, so you need to work with an absolute path.

    0 讨论(0)
提交回复
热议问题