PHP - 数组中的新对象

时间:2012-07-01 17:43:11

标签: php arrays class

class Player 
{
    public $name;
    public $stack;
    public $action;

    public function __construct($stack, $action)
    {
        $this->action = $action;
        $this->stack = $stack;
    }

}

class Hand
{
    public $BB;
    public $SB;
    public $ante;
    public $isSB = TRUE;
    public $hero = 1;

    public $players = array(
        new Player(1800,200);
        new Player(2000,0);
        new Player(2400,100);
        new Player(2600,200);
    );

}


$h = new Hand();
echo $h->players[$h->hero]->stack;

我得到了解析错误。 解析错误:语法错误,意外T_NEW,期待')'在... 如何将对象添加到此数组?有更好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

您需要将其移至构造函数

class Hand
{
    public $BB;
    public $SB;
    public $ante;
    public $isSB = TRUE;
    public $hero = 1;

    public $players ;

    public function __construct()
    {
        $this->players = array(
           new Player(1800,200),
           new Player(2000,0),
           new Player(2400,100),
           new Player(2600,200),
        );
    }

}