简体   繁体   中英

PHP Traits: How to resolve a property name conflict?

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 !

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'
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM