如何从一类中获取常量,但不包括可能从父代派生的所有常量? [英] how to get constants from a class excluding all constants that may have been descended from parents?

查看:56
本文介绍了如何从一类中获取常量,但不包括可能从父代派生的所有常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在第二个示例中,PDO用其常量填充MyClass,如何将其过滤掉?

here in second example PDO is populating MyClass with it's constants, how to filter them out ?

class MyClass {
  const PARAM_1 = 1;
  const PARAM_2 = 2;
  const PARAM_3 = 4;

  function MyMethod() {
    $reflector = new ReflectionClass(__CLASS__);
    print_r($reflector->getConstants());
  }

}

$myInstance = new MyClass();
$myInstance->MyMethod();

//returns:
//Array
//(
//    [PARAM_1] => 1
//    [PARAM_2] => 2
//    [PARAM_3] => 4
//)

class MyClassPDO extends PDO {
  const PARAM_1 = 1;
  const PARAM_2 = 2;
  const PARAM_3 = 4;

  function MyMethod() {
    $reflector = new ReflectionClass(__CLASS__);
    print_r($reflector->getConstants());
  }

}

$myInstancePDO = new MyClassPDO('sqlite::memory:');
$myInstancePDO->MyMethod();

//Array
//(
//    [PARAM_1] => 1
//    [PARAM_2] => 2
//    [PARAM_3] => 4
//    [PARAM_BOOL] => 5
//    [PARAM_NULL] => 0
//    [PARAM_INT] => 1
//    [PARAM_STR] => 2
//    [PARAM_LOB] => 3
//    [PARAM_STMT] => 4
//    [PARAM_INPUT_OUTPUT] => -2147483648
//    [PARAM_EVT_ALLOC] => 0
//    [PARAM_EVT_FREE] => 1
//    [PARAM_EVT_EXEC_PRE] => 2
//....and so on

推荐答案

AFAIK

function MyMethod() {
  $reflector = new ReflectionClass(__CLASS__);
  print_r(array_diff($reflector->getConstants(),$reflector->getParentClass()->getConstants()));
}

这篇关于如何从一类中获取常量,但不包括可能从父代派生的所有常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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