PHP特性:如何解决属性名称冲突? [英] PHP Traits: How to resolve a property name conflict?

查看:143
本文介绍了PHP特性:如何解决属性名称冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当类使用两个具有同名属性的特征时,如何解决属性名称冲突?

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

示例:

<?php

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


trait Audio {

    public $name = 'a';
}


class Media {
    use Audio, Video;
}

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

我尝试用( Video :: name代替Audio )和( Video :: name as name2 )失败了.

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

提前谢谢!

推荐答案

您不能,仅适用于方法.
但是,只有在值相同的情况下,它们才可以使用相同的属性名称:

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

这篇关于PHP特性:如何解决属性名称冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆