2012-01-05 206 views
0

我无法将函数声明为数组。这是我的代码,我做错了什么?将函数添加到数组中php

private function array_list(){ 
    return array('1'=>'one', '2'=>'two'); 
} 

private $arrays= array(
    'a'=>array('type'=>'1', 'list'=>$this->array_list()) 
); 

运行此代码时出现意外的T_VARIABLE错误。

+0

请提供全班。 – davogotland 2012-01-05 00:47:37

+0

http://stackoverflow.com/questions/1499862/can-you-store-a-function-in-a-php-array – c69 2012-01-05 00:47:41

+0

在定义类的属性时,不能使用变量。在属性定义中提供的所有内容都必须是(不变的,而不是动态的)。 – Kenaniah 2012-01-05 01:00:59

回答

0

做一个方法,例如,构造函数:

class Foo { 
    function __construct() { 
     $this->arrays['list'] = $this->array_list(); 
    } 
} 
1

你不能像这样的声明数组财产:

private $arrays= array(
    'a'=>array('type'=>'1', 'list'=>$this->array_list()) 
); 

不能使用数组从类方法返回的属性定义。例如,您应该将其填充到构造函数中。像这样:

private $arrays = array(); 

public function __construct() { 
    $this->arrays = array(
     'a'=>array('type'=>'1', 'list'=>$this->array_list()) 
    ); 
} 
+0

谢谢!效果很好 – user389767 2012-01-05 01:15:40