类的多个实例并读取它们的PHP

时间:2019-07-07 06:26:06

标签: php class

我陷入了一个问题,我正在学习一个PHP OOP,并尝试一个包含所有已初始化一次的所有播放器的make类,然后我可以通过调用基于ID的任何实例(例如Player :)从任何地方获取数据: GetInstance($ id)

class Player
{
    private $id;
    private $name;
    private $level;

    function __construct($id, $name)
    {
        //self::$instances[] = $this;
        $this->name = $name;
        $this->id = $id;
    }

    public function setLevel($level)
    {
        $this->level = $level;
    }

    public function getData()
    {
        $data = array($this->id, $this->name, $this->level);
        return $data;
    }
}


$player1 = new Player(1, "Henry");
$player2 = new Player(2, "Mike");


$player1->setLevel(5);
$player2->setLevel(10);


在另一个文件或另一个功能中 我想从一审获取数据

$player = Player::Id(1)->GetData() f.e.

function GetPlayerDataById($id)
{

..
}

1 个答案:

答案 0 :(得分:0)

您需要将所有玩家放在一个数组中,并定义一个静态方法来按ID查找玩家。

class Player
{
    private $id;
    private $name;
    private $level;

    private static $instances = [];

    function __construct($id, $name)
    {
        self::$instances[$id] = $this;
        $this->name = $name;
        $this->id = $id;
    }

    public function setLevel($level)
    {
        $this->level = $level;
    }

    public function getData()
    {
        $data = array($this->id, $this->name, $this->level);
        return $data;
    }

    public static Id($id) {
        if (isset(self::$instances[$id])) {
            return self::$instances[$id];
        } else {
            return null;
        }
    }
}