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条)

报告相同问题?

悬赏问题

  • ¥20 基于决策树的数字信号处理,2ask 2psk 2fsk的代码,检查下报错的原因
  • ¥20 python作业求过程
  • ¥15 wincc已组态的变量过多
  • ¥60 如图:直线与椭圆X轴平行,求直线与椭圆任意一点的相切坐标计算公式
  • ¥50 如何用python使用opencv里的cv::cudacodec::VideoWriter函数对视频进行GPU硬编码
  • ¥100 c#solidworks 二次开发 工程图自动标边线法兰 等折弯尺寸怎么标
  • ¥15 halcon DrawRegion 提示错误
  • ¥15 FastAPI Uvicorn启动显示404
  • ¥15 centos7.9脚本,怎么排除特定的访问记录
  • ¥15 关于#Django#的问题:我的静态文件呢?