如何正确地为PHP类中的私有静态变量赋值?

时间:2013-02-24 02:01:16

标签: php

我有一个翻译语言数组库的类。所以问题是语言不会根据cookie值改变。

此函数应设置语言值但不设置。似乎无论我做什么,我总是得到“ar”作为自我:: $ currlang值。我该如何纠正这个问题?

public function _set(){

    if( $_COOKIE['defaultLang'] != '' ) {
        self::$currlang = $_COOKIE['defaultLang'];
    } else {
        //this is the default language
        self::$currlang = 'ar';
    }

}

这是我的代码

感谢您的帮助:)

<?php
include('../langs/english.php');
include('../langs/arabic.php');

class Translator{
    private static $strs = array();
    private static $currlang = "";


    public function _set(){

        if( $_COOKIE['defaultLang'] != '' ) {
            self::$currlang = $_COOKIE['defaultLang'];
        } else {
            //this is the default language
            self::$currlang = 'ar';
        }

    }


    public static function loadTranslation($lang, $strs){
        if (empty(self::$strs[$lang]))
            self::$strs[$lang] = array();

        self::$strs[$lang] = array_merge(self::$strs[$lang], $strs);        
    }

    public static function setDefaultLang($lang){
        self::$currlang = $lang;        
    }

     public static function getDefaultLang(){
        return self::$currlang;        
    }

    public static function translate($key, $lang=""){
        if ($lang == ""){
            $lang = self::$currlang;
        }
        $str = self::$strs[$lang][$key];
        if (empty($str)){
            //$str = "$lang.$key"; 
            $str = 'Language "'. $lang . '", '. $key . ' is not defined.';           
        } 
        return $str;       
    }    

    public static function freeUnused(){
        foreach(self::$strs as $lang => $data){
            if ($lang != self::$currlang){
                $lstr = self::$strs[$lang]['langname'];
                self::$strs[$lang] = array();
                self::$strs[$lang]['langname'] = $lstr;                
            }            
        }        
    }

    public static function getLangList(){
        $list = array();
        foreach(self::$strs as $lang => $data){
            $h['name'] = $lang;
            $h['desc'] = self::$strs[$lang]['langname'];
            $h['current'] = $lang == self::$currlang;
            $list[] = $h;
        }
        return $list;        
    }

    public static function &getAllStrings($lang){
        return self::$strs[$lang];
    }

}

?>

1 个答案:

答案 0 :(得分:1)

_set()魔术方法适用于 - &gt;运算符,与实例化对象一起使用。您不能将静态成员变量与实例化对象一起使用,它是一个或另一个。