PHP特性-定义泛型常量 [英] PHP traits - defining generic constants

查看:60
本文介绍了PHP特性-定义泛型常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义常量的最佳方法是什么?命名空间中的多个类都可以使用常量?我试图避免过多的继承,因此扩展基类不是理想的解决方案,并且我正努力使用traits寻找一个好的解决方案.在PHP 5.4中这是否有可能,还是应该采用其他方法?

What is the best way to define constants that may be used by a number of classes within a namespace? I'm trying to avoid too much inheritance, so extending base classes is not an ideal solution, and I'm struggling to find a good solution using traits. Is this in any way possible in PHP 5.4 or should a different approach be taken?

我有以下情况:

trait Base
{
    // Generic functions
}

class A 
{
    use Base;
}

class B 
{
    use Base;
}

问题在于无法在PHP特性中定义常量.理想情况下,我想要以下内容:

The problem is that it is not possible to define constants in PHP traits. Ideally, I would want something like the following:

trait Base
{
    const SOME_CONST = 'someconst';
    const SOME_OTHER_CONST = 'someotherconst';

    // Generic functions
}

然后可以通过应用特征的类来访问它们:

Then these could be accessed though the class that applies the trait:

echo A::SOME_CONST;
echo B::SOME_OTHER_CONST;

但是由于特征的限制,这是不可能的.有什么想法吗?

But due to the limitations of traits this isn't possible. Any ideas?

推荐答案

我最终使用了 user sectus对接口的建议,因为这似乎是解决问题的最简单的方法.尽管使用一个接口存储常量而不是API协定有一个不好的味道,所以也许这个问题更多的是关于OO设计而不是特征实现.

I ended up using user sectus's suggestion of interfaces as it feels like the least-problematic way of handling this. Using an interface to store constants rather than API contracts has a bad smell about it though so maybe this issue is more about OO design than trait implementation.

interface Definition
{
    const SOME_CONST = 'someconst';
    const SOME_OTHER_CONST = 'someotherconst';
}

trait Base
{
    // Generic functions
}

class A implements Definition
{
    use Base;
}

class B implements Definition
{
    use Base;
}

允许:

A::SOME_CONST;
B::SOME_CONST;

这篇关于PHP特性-定义泛型常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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