PHP Traits: How to resolve a property name conflict?

守給你的承諾、 提交于 2019-12-22 07:58:08

问题


How to resolve a property name conflict when a class uses two Traits with homonymous properties?

Example:

<?php

trait Video {
    public $name = 'v';
}


trait Audio {

    public $name = 'a';
}


class Media {
    use Audio, Video;
}

$media = new Media();
$media->name;

I've tried insteadof (Video::name insteadof Audio) and (Video::name as name2) without success.

Thanks in advance !


回答1:


You can't, its for methods only.
However they may use the same property name only if the value is the same:

trait Video {
  public $name;
  function getName(){
    return 'Video';
  }
}
trait Audio {
  public $name;
  function getName(){
    return 'Audio';
  }
}
class Media {
  use Audio, Video {
    Video::getName insteadof Audio;
  }

  function __construct(){
    $this->name = $this->getName(); // 'Video'
  }
}


来源:https://stackoverflow.com/questions/41679384/php-traits-how-to-resolve-a-property-name-conflict

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!