简体   繁体   中英

Store a PHP variable once throughout a webpage.

So I have aa variable called json that stores all of the json. I want to load this once in the site, and be able to use it through any php function that I have. So let's say I have this line of code placed at the beginning of index.php:

  $json = file_get_contents('http:/xxxxxxxx/bp.json');

I want to be able to use this variable from a function somewhere else in the page, WITHOUT loading it again.

Thanks!

You could store your variables in the PHP session and call it anywhere in your application.

$_SESSION["favcolor"] = "green";

http://www.w3schools.com/php/php_sessions.asp

Also best practices is to destroy and/or clear all your session variables upon exiting your application.

1) Use global variables

<?php
$myVar = 1;
function myFunction()
{
    global $myVar;
    $myVar  = 2;
} 

myFunction();
echo $myVar; //will be 2

include 'another.php'; //you can use $myVar in another.php too.
?>

variables PHP manual

2) Use cookies

If you want your variable to be access from any browser window or after loading another page, you have to use COOKIES since HTTP is stateless. These cookies can be accessed via javascript since those are stored in client side browser and can be accessed by client.

<?php 
setcookie("myVar","myValue",time()+86400);
/*
   86400 is time of cookie expires. (1 day = 86400)
*/
?>


<?php 
/* 
   Getting cookie from anywhere 
*/
$myVar = $_COOKIE["myVar"];
echo $myVar;
?>

cookies PHP manual

3) Use a session

Best method to store your variables in server side which is secure than using cookies directly is by using a HTTP_SESSION

<?php
/* 
   Start a session. 
   Call this line top of every page you want to use session variables 
*/
session_start();
// set variable
$_SESSION["myVar"] = "value";
?>

<?php
session_start();
// Access session variables from another php.
$myVar = $_SESSION["myVar"];
?>

sessions PHP manual

A simple way do this ,you can use Superglobals

Superglobals — Superglobals are built-in variables that are always available in all scopes

I think you must used supergloabls variables before like $_SERVER,$_GET,$_POST etc,and supergloabls variables also include $GLOBALS.

What is $GLOBALS

Note: Variable availability Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.

So you can do this

  1. Get data from json file
  2. Assign data to $GLOBALS
  3. User $GLOBALS variable instead of $json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM