简体   繁体   English

php一个特定类的数组或列表

[英]php an array or list of a specific class

I would need a class like: 我需要一个类:

<?php
class  Replay{

    private $id;
    private $nickname;


    public function setId($id_){
       $this->id = $id_;
    }
    public function setNickname($nickname_){
       $this->nickname = $nickname_;
    }

    public function getId(){
       return $this->id;
    }
    public function getNickname(){
       return $this->nickname;
    }
}
?>

and than I would make another class replays that would hold an array of replay. 而且我会做另一个可以举行重播的课程重播。 (repository) (资料库)

I don`t know how to declare the array of replay, if anyone has some examples? 如果有人有一些例子,我不知道如何宣布重播阵列? even more complex with sorting and other functions if now only the basic stuff. 如果现在只有基本的东西,甚至更复杂的排序和其他功能。

<?php
class  Replays{

    private $number;  //number of elements
    ...
?>

You would just create an array and add to them as needed: 您只需创建一个数组并根据需要添加它们:

<?php
class Replays {
    private $replays = array();

    public function addReplay($replay){
        replays[] = $replay;
    }

    public function getNumReplays(){
        return count($replays);
    }

}
?>

Not sure if you are used to java, but arrays in php do not need to know the type they are holding. 不确定你是否习惯了java,但php中的数组不需要知道它们持有的类型。 For example and array can hold strings and integers at the same time: 例如,数组可以同时保存字符串和整数:

<?php
$array = array("string", 2, 2.0);
var_dump($array);

?>

Output: 输出:

array(3) {
  [0] =>
  string(6) "string"
  [1] =>
  int(2)
  [2] =>
  double(2)
}

As you can see PHP understands the types and they can all be in the same array. 正如您所看到的,PHP了解类型,它们都可以在同一个数组中。

In PHP arrays do not carry a particular type. 在PHP中,数组不带特定类型。 So you can simply declare an array as 所以你可以简单地将数组声明为

$repo = array ();

and then add multiple entries to it 然后向其中添加多个条目

$repo[] = new Replay();
$repo[] = new Replay();
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM