duanjigua5753 2015-01-23 10:37
浏览 49
已采纳

PHP数组,只包含特定类的对象

I have a class called Rule and I'm about to create a RuleContainer class that's actually an array of Rule objects.

I wonder if there is an alternative of creating a new class. Is there any (modern) way to approach this problem? That is, something like using SPL to define an array that only allows adding objects of a specific class.

If not, which interface should I implement in my RuleContainer class?

  • 写回答

5条回答 默认 最新

  • dongwen9975 2015-01-23 10:57
    关注

    The most suitable class for your task would be SplObjectStorage, but it doesn't allow for class typehint.

    I think, you could do as follow:

    class RuleContainer extends SplObjectStorage
    {
        function attach(Rule $rule)
        {
             parent::attach($rule);
        }
    
        function detach(Rule $rule)
        {
             parent::detach($rule);
        }
    }
    

    and so on. You can read for SplObjectStorage interface on php.net and decide, what will you use and what needs overriding.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

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