我正在尝试使用以下PHP类:
<?php
class Service {
public $code, $description;
public static $services = array(
"A" => "Shipping",
"B" => "Manufacturing",
"C" => "Legal",
"D" => "Accounts Receivable",
"E" => "Human Resources",
"F" => "Security",
"G" => "Executive",
"H" => "IT"
);
public function _construct( $c, $d) {
$this->code = $c;
$this->description = $d;
}
public static function getDescription( $c ){
return $services[$c];
}
public static function generateServiceList() {
$service_list[] = array();
foreach ($services as $k => $v ){
$service_list[] = new Service( $k, $v );
}
return $service_list;
}
}
?>
......以下列方式:
<?php
$services = Service::generateServiceList();
?>
...但收到以下错误:
Warning: Invalid argument supplied for foreach() in /classes/service.php on line 31
知道为什么吗?这是某种访问问题吗?感谢。
答案 0 :(得分:5)
$services
未定义。你的意思是self::$services
吗?
答案 1 :(得分:1)
$services
变量在函数外声明。使用类时,您必须使用$this
关键字来访问它:
...
foreach ($this->services as $k => $v ){
...
稍后修改:对于静态变量,请使用self::$services
代替$this->services
。
答案 2 :(得分:1)
foreach ($services as $k => $v ){
$service_list[] = new Service( $k, $v );
}
到
foreach ($this->services as $k => $v ){
$service_list[] = new Service( $k, $v );
}
您想要引用Class的$ services而不是函数的本地$ services。
答案 3 :(得分:0)
我现在无法测试它,但我的直觉是移动$service
没有被实例化。在这种情况下,我倾向于使用init
变量的方法。在这种情况下,您可以创建另一个方法
$services = array(
"A" => "Shipping",
"B" => "Manufacturing",
"C" => "Legal",
"D" => "Accounts Receivable",
"E" => "Human Resources",
"F" => "Security",
"G" => "Executive",
"H" => "IT"
实例化。