如何从php中的方法返回变量和数组?

时间:2013-02-19 22:15:36

标签: php arrays variables methods return

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 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分: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);
}

答案 2 :(得分: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;

答案 3 :(得分: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'];