PHP - 如何引用驻留在对象内的另一个对象的类变量(属性)?

Maybe the question is a little confusing, lets use an example:

Let's say I have an object (class) of Team.

Inside the class I have a class property which is an object (class) of Player and I want to access his jerseyNumber property, how do I do this?

class Team {
    public $player;
}

class Player {
    public $jerseyNumber;
}

Bare in mind, I'm new to PHP.

To access a property inside Team, I would just use:

$team->player;

But it doesn't seem like I can access a property inside player like this (which I'd think would work considering the above):

$team->player->jerseyNumber;

So how do I access jerseyNumber?

Modify your code to this. I have added a constructor inside Team. This will help you instantiate the player class inside team class properly as the team class is instantiated. You can then access player properties with team object easily.

PS Instantiating a class means creating an object of the class.

You will still need to write code to assign values to $jerseyNumber.

class Team {
public $player;



public function  __construct(){
  $this->player = new Player();
    }
}

class Player {
    public $jerseyNumber;
}

$team = new Team;

echo $team->player->jerseyNumber;