seyed ali ziaei
seyed ali ziaei

Reputation: 198

get value from static variable of class in different PHP files

I do try to get static variable of php class in different php files. but when set variable in testpy.php then variable in taski.php is null.

This is testpy.php:

<?php
/**
 * Created by PhpStorm.
 * User: PC1
 * Date: 9/16/2018
 * Time: 3:00 PM
 */
include 'cacheData.php';
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_ERROR);
//echo $_POST["firstname"];
cacheData::$cacheArrayFirst = json_decode($_POST["firstname"]);
cacheData::converting(cacheData::$cacheArrayFirst);
echo json_encode(cacheData::$cacheArrayFinal);

this is taski.php:

<?php
/**
 * Created by PhpStorm.
 * User: hamed
 * Date: 17/09/2018
 * Time: 12:37
 */
include 'cacheData.php';
sleep(5);
echo json_encode(cacheData::returnValue());

this is cacheData.php:

<?php
/**
 * Created by PhpStorm.
 * User: PC1
 * Date: 9/16/2018
 * Time: 4:35 PM
 */

class cacheData
{
    public static $cacheArrayFirst;
    public static $cacheArrayFinal;
    public static function converting($cacheArrayOne){
        if (empty(cacheData::$cacheArrayFinal)){
            cacheData::$cacheArrayFinal=$cacheArrayOne;
        }
    }

    public static function returnValue(){
        return self::$cacheArrayFinal;
    }
}

Upvotes: 1

Views: 245

Answers (1)

Alex Shesterov
Alex Shesterov

Reputation: 27595

You never call testpy.php from taski.php in any way. Therefore, when taski.php is executed, the code from testpy.php is never run, so the variables are not set.

You could, for example, include testpy.php in taski.php:

<?php
include 'cacheData.php';
include 'testpy.php'; // <-Added
sleep(5);
echo json_encode(cacheData::returnValue());

Possibly, you attempt to access the static variables set by the previous HTTP-call to testpy.php, from taski.php. The sleep could indicate this. It won't work — every HTTP request is a new execution of the PHP application, so all the static variables are reset.

If you need to "preserve" some values between the requests, you need to store tha values in a database, on local drive or in another kind of storage. You can also consider using sessions.

See also: PHP Persist variable across all requests

Upvotes: 3

Related Questions