duanqiang2617 2016-01-20 17:44
浏览 71

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?

  • 写回答

1条回答 默认 最新

  • dongtu4028 2016-01-20 18:42
    关注

    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;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分