Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中将值推送到数组中_Php_Arrays - Fatal编程技术网

在PHP中将值推送到数组中

在PHP中将值推送到数组中,php,arrays,Php,Arrays,我在接收我要推入卡阵列的值时遇到问题。我不知道是我没有调用正确的属性,还是我只是没有正确地添加到数组中 <?php class Deck{ public function __construct(){ $values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A'); $suits =array('Diamond','Club','Heart','Spade');

我在接收我要推入卡阵列的值时遇到问题。我不知道是我没有调用正确的属性,还是我只是没有正确地添加到数组中

<?php

class Deck{

    public function __construct(){
        $values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A');
        $suits =array('Diamond','Club','Heart','Spade');
        $cards = array();
        foreach ($suits as $suit) {
            foreach($values as $value){
                $cards[] = "$value of $suit's";
            }
        }
    }
}

$deck = new Deck();
var_dump($deck);

$cards
\u构造的局部变量:一旦该函数结束,该变量就会消失。相反,您可能希望使
卡成为该类的成员:

class Deck {
    public $cards = [];

    public function __construct() {
        $values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A');
        $suits =array('Diamond','Club','Heart','Spade');
        $cards = array();
        foreach ($suits as $suit) {
            foreach($values as $value){
                $this->cards[] = "$value of $suit's";
            }
        }
    }
}

然后,您可以在对象内部使用
$this->cards
,或在对象外部使用
$deck->cards

在$cards[]=“$suit's的$value”。。是打字错误吗?$cards[]=$value.“..$suites<代码>$deck
是您的对象。在构造函数中有一个局部变量
$cards
保存创建的数组。只需打印($cards)在构造函数内部?!然后做var_转储($deck->cards)?