class Assignation {
private $VVal_1 = 1;
private $VNam_1 = "One";
//....Multiple Items
private $VVal_2000 = 2000; //For Example
private $VNam_2000 = "Two Thousands"; //For Example
private static $Hash = array(); //How to initialize???
private static function Assigning(){
//This function for to assign the array elements (initialize)
global $Hash;
$this->Hash = array(); //to empty Hash variable and not add more data than it should.
$this->Hash[$this->VVal_1] = $this->VNam_1;
//....Multiple Items
$this->Hash[$this->VVal_2000] = $this->VNam_2000;
}
public static function GetVal($Nam) {
$this->Assigning(); //or use self::Assigning(); //I want to avoid this call
if (array_search($Nam, $this->Hash))
return array_search($Nam, $this->Hash);
return -1;//error
}
public static function GetNam($Val) {
$this->Assigning(); //or use self::Assigning(); //I want to avoid this call
if (array_key_exists($Val, $this->Hash))
return $this->Hash[$Val];
return "Error";
}
}
Class Testing {
static $OtherVal = Assignation::GetVal("BLABLA"); //for example
static $OtherNam = Assignation::GetNam(20); //for example
//Other functions...
}嗨,你可以看到我的脚本或代码php.我需要初始化Hash数组,这个数组有静态字,因为我需要在其他静态函数中使用它。这个“其他函数”需要用于其他静态变量..。我需要知道如何用正确的方式实现它。
谢了切普-。
<?php
echo "pre-Class Assignation<br/>";
class Assignation {
private $VVal_1 = 1;
private $VNam_1 = "One";
private $VVal_2K = 2000;
private $VNam_2K = "Two Thousands";
private static $Hash = array();
private static function Assigning(){
if(!empty(self::$Hash)) return;
self::$Hash[$this->VVal_1] = $this->VNam_1;
self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}
public static function GetVal($Nam) {
self::Assigning();
if (array_search($Nam, self::$Hash)) return array_search($Nam, self::$Hash);
return -1;//error
}
public static function GetNam($Val) {
self::Assigning();
if (array_key_exists($Val, self::$Hash)) return self::$Hash[$Val];
return "Error";
}
}
echo "post-Class Testing<br/>";
echo Assignation::GetVal("BLABLA");
echo "post-Class Mid<br/>";
echo Assignation::GetNam(20);
echo "post-Class Sample<br/>";
//Testing::MyPrint();
?>这段代码没有运行,有人帮我测试代码.结果:
pre-Class Assignation
post-Class Assignation
post-Class Testing意思是:“回声分配::GetVal(”BLABLA“);”有错误.
发布于 2011-08-18 01:48:51
在Assigning()中,尝试使用self::$Hash而不是$this->Hash并删除global $Hash。正如您的评论所建议的那样,调用Assigning():self::Assigning()也是如此。
$this引用当前对象,因此在类内必须对所有静态函数和成员数据使用self::。
另外,如果这是真正的代码,而不仅仅是一个示例,您可能需要检查您是否已经完成了初始化,否则您将对GetVal()和GetNam()进行每次调用。您可以通过在if(!empty(self::$Hash)) return开头添加类似于Assigning()的内容来实现这一点。
编辑
private static function Assigning() {
if(!empty(self::$Hash)) return; // already populated
self::$Hash = array();
self::$Hash[$this->VVal_1] = $this->VNam_1;
//....Multiple Items
self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}https://stackoverflow.com/questions/7101461
复制相似问题