How to make a nested class in PHP?

I'm new at PHP developing and I'm completely lost about how PHP handles classes and inheritance. As I've read, there are no nested classes in PHP. I'm coming from C#, and I'd like to reproduce the following structure:

private class GameScore {
        public TeamData[] teams =  new TeamData[2];                      
        public Boolean alert { get; set; }
        public String date { get; set; }
        public String time { get; set; }
        public class TeamData {                
            public String name { get; set; }
            public String score { get; set; }
        }
    }

Every GameScore should have the name of the teams who played the match and the score they got in the given match. I'd like to be able to store this data in the following way, to list several scores of multiple matches:

GameScore[] game = new GameScore[n];

game[0].alert = true;
game[0].date = "Oct. 17";
game[0].time = "15:25 EST";
game[0].teams[0].name = "Toronto Raptors";
game[0].teams[0].score = "0";
game[0].teams[1].name = "New York Knicks";
game[0].teams[1].score = "0";

...

EDIT: I tried the following structure:

class TeamData{
    public $name;
    public $score;

    public function __construct() {
        $this->name = '';
        $this->score = '';
    }
}

class GameScore{
    public $alert;
    public $date;
    public $time;

    public $team1;
    public $team2;

    function __construct(){
        $this->alert = false;
        $this->date = '';
        $this->time = '';
        $this->team1 = new TeamData();
        $this->team2 = new TeamData();
    }
}

Whereas this replicates the same structure written in C#, it doesn't generates any dependency between GameScore and TeamData (for example I need to instantiate GameScore.TeamData if I want to access this data type on C#, which is not the case on PHP using the above code)

What's the correct way to achieve this?

Upvotes: 3

Views: 2210

Answers (2)

SomeNorwegianGuy
SomeNorwegianGuy

Reputation: 1534

Php does not support nested classes If TeamData does not need access to members of GameScore, you can write them as two separate classes, which seems to be the case. And php has no built in get/set keywords, so getters and setters needs to be written manually.

Upvotes: 0

Michal Przybylowicz
Michal Przybylowicz

Reputation: 1668

Familiarize Yourself with traits in php:

https://secure.php.net/manual/en/language.oop5.traits.php

Upvotes: 2

Related Questions