0

php n00b 在这里:

我正在尝试从一副牌中挑选一张牌。

类实例是“$test_1”,函数“pick_card”是该类的方法。

我希望函数返回 1)我想要的卡片,以及 2)套牌,减去一张卡片。

我哪里错了?

$card, $deck = $test_1->pick_card($play_deck);

public function pick_card(&$deck)
{
    $card = $deck[0];
    echo "picked this card: " . $card . "<br />";
    array_splice($deck,0,0);
    return $card; $deck;
}
4

4 回答 4

3

你不能在 PHP 中返回两个这样的变量。我注意到您是通过$deck引用传递给函数的,因此您对该变量所做的任何修改都将在函数对其进行操作时反映在该变量中。

话虽这么说,因为这是一个类,你真的不应该传递一个变量,你真的应该有一个存储你的牌组的属性。我会建议这样的事情:

class card_deck {
    protected $deck = NULL;

    public function __construct() {
        // some logic to create, shuffle, and set deck array to $this->deck
    }

    public function pick_card() {
        if($this->get_card_count() < 1) {
            throw new Exception('The deck is empty.');
        }
        return array_shift($this->deck);
    }

    public function get_card_count() {
        return count($this->deck);
    }
}
于 2013-02-19T22:24:04.033 回答
2

您必须将其作为数组返回。您可以使用关联数组,也可以使用list将数组拆分为如下变量:

list($card, $deck) = $test_1->pick_card($play_deck);

public function pick_card(&$deck)
{
    $card = $deck[0];
    echo "picked this card: " . $card . "<br />";
    array_splice($deck,0,0);
    return array($card, $deck);
}
于 2013-02-19T22:26:59.827 回答
1

因为你有一个对象,你也可以使用$this

class card_deck {
  public $card;
  public $deck;
  public function pick_card(&$deck) {
    $this->card = $deck[0];
    $this->deck = $deck;
    echo "picked this card: " . $this->card . "<br />";
    array_splice($this->deck,0,0);
  }
}

$test_1 = new card_deck();
//set $play_deck 
$test_1->pick_card($play_deck);

// now use
$test_1->card;
$test_1->deck;
于 2013-02-19T22:28:53.303 回答
0

您可以在关联数组中返回所需的值。我认为您熟悉数组,就像您在函数中使用deck[0]的那样pick_card

class Foo{
    public function pick_card(&$deck){
        $card = $deck[0];
        echo "picked this card: " . $card . "<br />";
        array_splice($deck,0,0);
        return array('card'=>$card,'deck'=>$deck);
    }
}
$test_1 = new Foo;
$deck = $test_1->pick_card($play_deck);
echo 'Card: '.$deck['card'].'<br>';
echo 'Deck: '.$deck['deck'];
于 2013-02-19T22:23:09.757 回答