How do I make a nested class in PHP?

I'm new to PHP development and I am completely lost about how PHP handles classes and inheritance. As I read before, there are no nested classes in PHP. I am coming from C # and I would 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; }
        }
    }

      

Each GameScore must have the name of the teams that played the match and the score they received in that match. I would like to store this data in the following way to list a few dozen 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've 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();
    }
}

      

While this replicates the same structure written in C #, it does not create any dependency between GameScore

and TeamData

(for example, I need to instantiate GameScore.TeamData

if I want to access this data type in C #, which is not the case for PHP since using the above code)

What's the correct way to achieve this?

+3


source to share


2 answers


Read traits

in php

:



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

+2


source


Php doesn't support nested classes If TeamData doesn't need access to GameScore members, you can write them as two separate classes, which seems to be the case. And php doesn't have get / set keywords built in, so getters and setters have to be written by hand.



0


source







All Articles