从Ajax访问私有静态类属性

时间:2013-11-06 23:14:56

标签: php ajax singleton

我有一个类似的课程:

class My_Class {
    private static $array = null;
    private static $another_array = null;

    private function __construct() {
        self:$another_array = array( 'data' );
    }

    // This gets executed from jQuery Ajax when user clicks a button
    public static function process_ajax() {
        self::generate_html();
    }

    private static function generate_html() {
        if ( ! self::$array ) {
            self::$array = array( 'some data' );
        }
    }

    // This gets executed when user is trying to save Ajax generated form
    public static function save_ajax_form() {
        print_r( self::$another_array ); // prints [0] => 'data'
        self::validate_data();
    }

    private static function validate_data() {
        // WHY DOES THIS EVALUATE TRUE? 
        if ( ! is_array( self::$array ) ) {

        }

    }
}

如何从Ajax调用中访问My_Class::$array属性?

2 个答案:

答案 0 :(得分:3)

即使您声明变量static,它也会在每个请求上初始化为null - PHP以这种方式“无状态”,静态变量不会在请求中保持不变。由于您确实希望保留该值,因此需要使用$_SESSIONAPCmemcached之类的值来保存$array的值。

当您的ajax立即调用save_ajax_form()时,会调用validate_data()。由于对$array的调用发生在另一个请求中,generate_html()变量仍然初始化为null,因此检查它是否不是数组将返回true。

请参阅:Does static variables in php persist across the requests?

答案 1 :(得分:0)

显然,您可以将范围声明从private更改为public,或者如果您想保密,请添加公共访问者:

public function getArray()
{
    self::process_ajax();

    return self::$array;
}