简体   繁体   中英

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. 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.

In PHP arrays do not carry a particular type. So you can simply declare an array as

$repo = array ();

and then add multiple entries to it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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