douti9253 2012-12-07 15:33
浏览 18
已采纳

PHP测试数组实例中是否存在类实例

I've got a Collection of closely related Objects. Before I add an Object to the collection, I want to check the class instance to make sure it's OK.

Normally, I like all my objects in a collection to have a similar baseClass OR interface so I can use type hinting but in this case, the objects aren't like that.

I like the way instanceof works. I don't want to have to manage a list of namespaces.

  • 写回答

1条回答 默认 最新

  • dongyu1125 2012-12-07 15:33
    关注

    Using the new 5.4 [] for array() syntax - create an array of valid classnames:

    private $validClasses = ['MyFirstClass','MySecondClass','MyThirdClass'];
    

    Next, create a function to test.

    public function testClass($class){
        $arr = explode("\\", get_class($class) );
        if ( !in_array( array_pop($arr) , $this->validClasses  ) ){
        throw new \Exception('Invalid Class - Cannot be added to the Collection.');
         }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数