在一个类中,我有2个关联数组。我试图调用一个数组中的元素用于另一个(一种主类)数组。
我想问下列是否可以做,或不能,或者我做错了什么;
请注意,阵列就是例子。
class ProductData {
private $texture = [0=>'Cream', 1=>'Powder', 2=>'Liquid', 3=>'Paste', 4=>'Solid'];
private $food = ['type'=>'Pasta', 'info'=>[1=>'750gm', 2=>'$4.50', 3=>$this->texture[4]],
'type'=>'Soup', 'info'=>[1=>'500ml', 2=>'$7.60', 3=>$this->texture[2]]];
// Constructor, Function(s) to access the $food array...
}
我发现这是不可能做到的。我收到语法错误;
如果我用$ texture替换$ this,我会收到同样的错误;
我认为这不可能做到,或者我做错了什么,或两者兼而有之。
如果可以做到这一点,我们非常感谢任何帮助。
谢谢, NJC
答案 0 :(得分:1)
class ProductData {
private $texture;
private $food;
function __construct(){
$this->texture = [0=>'Cream', 1=>'Powder', 2=>'Liquid', 3=>'Paste', 4=>'Solid'];
$this->food = ['type'=>'Pasta', 'info'=>[1=>'750gm', 2=>'$4.50', 3=>$this->texture[4]],
'type'=>'Soup', 'info'=>[1=>'500ml', 2=>'$7.60', 3=>$this->texture[2]]];
//other construct stuff
}
}
答案 1 :(得分:0)
您只能使用常量值来定义类方法之外的属性值。因此,在您的情况下,您不能使用$this
变量,因为它引用当前对象实例。
您应该将初始化移至__construct
(这实际上是为了什么)
此声明可能包括初始化,但此初始化必须是常量值 - 也就是说,它必须能够在编译时进行评估,并且不能依赖于运行时信息。为了评估。